/*!
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * version=0.2.134; type=Beta; name=Amoeba; package=Full; date=Mon 04/15/2013;
  *
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  */
// fluid version - build time definition 
if (typeof fluidOptions === 'undefined') { window.fluidOptions = {}; } 
fluidOptions["fluidVersion"] = "version=0.2.134; type=Beta; name=Amoeba; package=Full; date=Mon 04/15/2013;"; 
 
// plugins and features - build time definition 
if (typeof fluidOptions === 'undefined') { window.fluidOptions = {}; } 
fluidOptions["bundledFixedPluginNames"] = " 'root', 'environment', 'env', 'utils', 'document', 'files', 'IO', 'sessionStore', 'sess', 'states', 'page', 'navigator', 'nav', 'bus', 'app',"; 
fluidOptions["bundledDependencyNames"] = " 'jQuery', 'jQueryDoTimeout', 'fluidGlobals', 'deployJava', 'assembleComplete',"; 
fluidOptions["bundledKernelPluginNames"] = " 'root',"; 
fluidOptions["bundledKernelFeatureNames"] = ""; 
fluidOptions["bundledCorePluginNames"] = " 'root', 'environment', 'utils', 'document', 'files', 'IO', 'sessionStore', 'states', 'app',"; 
fluidOptions["bundledCoreFeatureNames"] = " 'objectFactory', 'properties', 'dynamicExtend', 'fsa', 'sessionProperty', 'stateProperty', 'appBase',"; 
 
/*!
 * jQuery JavaScript Library v1.9.1
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2013-2-4
 */
(function( window, undefined ) {

// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
	// The deferred used on DOM ready
	readyList,

	// A central reference to the root jQuery(document)
	rootjQuery,

	// Support: IE<9
	// For `typeof node.method` instead of `node.method !== undefined`
	core_strundefined = typeof undefined,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,
	location = window.location,

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// [[Class]] -> type pairs
	class2type = {},

	// List of deleted data cache ids, so we can reuse them
	core_deletedIds = [],

	core_version = "1.9.1",

	// Save a reference to some core methods
	core_concat = core_deletedIds.concat,
	core_push = core_deletedIds.push,
	core_slice = core_deletedIds.slice,
	core_indexOf = core_deletedIds.indexOf,
	core_toString = class2type.toString,
	core_hasOwn = class2type.hasOwnProperty,
	core_trim = core_version.trim,

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Used for matching numbers
	core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,

	// Used for splitting on whitespace
	core_rnotwhite = /\S+/g,

	// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,

	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,

	// Matches dashed string for camelizing
	rmsPrefix = /^-ms-/,
	rdashAlpha = /-([\da-z])/gi,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	},

	// The ready event handler
	completed = function( event ) {

		// readyState === "complete" is good enough for us to call the dom ready in oldIE
		if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
			detach();
			jQuery.ready();
		}
	},
	// Clean-up method for dom ready events
	detach = function() {
		if ( document.addEventListener ) {
			document.removeEventListener( "DOMContentLoaded", completed, false );
			window.removeEventListener( "load", completed, false );

		} else {
			document.detachEvent( "onreadystatechange", completed );
			window.detachEvent( "onload", completed );
		}
	};

jQuery.fn = jQuery.prototype = {
	// The current version of jQuery being used
	jquery: core_version,

	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;

					// scripts is true for back-compat
					jQuery.merge( this, jQuery.parseHTML(
						match[1],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {
							// Properties of context are called as methods if possible
							if ( jQuery.isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[2] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || rootjQuery ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	},

	// Start with an empty selector
	selector: "",

	// The default length of a jQuery object is 0
	length: 0,

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	toArray: function() {
		return core_slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;
		ret.context = this.context;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	ready: function( fn ) {
		// Add the callback
		jQuery.ready.promise().done( fn );

		return this;
	},

	slice: function() {
		return this.pushStack( core_slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},

	end: function() {
		return this.prevObject || this.constructor(null);
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: core_push,
	sort: [].sort,
	splice: [].splice
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery.extend = jQuery.fn.extend = function() {
	var src, copyIsArray, copy, name, options, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function( deep ) {
		if ( window.$ === jQuery ) {
			window.$ = _$;
		}

		if ( deep && window.jQuery === jQuery ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( !document.body ) {
			return setTimeout( jQuery.ready );
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );

		// Trigger any bound ready events
		if ( jQuery.fn.trigger ) {
			jQuery( document ).trigger("ready").off("ready");
		}
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	isWindow: function( obj ) {
		return obj != null && obj == obj.window;
	},

	isNumeric: function( obj ) {
		return !isNaN( parseFloat(obj) ) && isFinite( obj );
	},

	type: function( obj ) {
		if ( obj == null ) {
			return String( obj );
		}
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ core_toString.call(obj) ] || "object" :
			typeof obj;
	},

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {
			// Not own constructor property must be Object
			if ( obj.constructor &&
				!core_hasOwn.call(obj, "constructor") &&
				!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
				return false;
			}
		} catch ( e ) {
			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.

		var key;
		for ( key in obj ) {}

		return key === undefined || core_hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	error: function( msg ) {
		throw new Error( msg );
	},

	// data: string of html
	// context (optional): If specified, the fragment will be created in this context, defaults to document
	// keepScripts (optional): If true, will include scripts passed in the html string
	parseHTML: function( data, context, keepScripts ) {
		if ( !data || typeof data !== "string" ) {
			return null;
		}
		if ( typeof context === "boolean" ) {
			keepScripts = context;
			context = false;
		}
		context = context || document;

		var parsed = rsingleTag.exec( data ),
			scripts = !keepScripts && [];

		// Single tag
		if ( parsed ) {
			return [ context.createElement( parsed[1] ) ];
		}

		parsed = jQuery.buildFragment( [ data ], context, scripts );
		if ( scripts ) {
			jQuery( scripts ).remove();
		}
		return jQuery.merge( [], parsed.childNodes );
	},

	parseJSON: function( data ) {
		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		if ( data === null ) {
			return data;
		}

		if ( typeof data === "string" ) {

			// Make sure leading/trailing whitespace is removed (IE can't handle it)
			data = jQuery.trim( data );

			if ( data ) {
				// Make sure the incoming data is actual JSON
				// Logic borrowed from http://json.org/json2.js
				if ( rvalidchars.test( data.replace( rvalidescape, "@" )
					.replace( rvalidtokens, "]" )
					.replace( rvalidbraces, "")) ) {

					return ( new Function( "return " + data ) )();
				}
			}
		}

		jQuery.error( "Invalid JSON: " + data );
	},

	// Cross-browser xml parsing
	parseXML: function( data ) {
		var xml, tmp;
		if ( !data || typeof data !== "string" ) {
			return null;
		}
		try {
			if ( window.DOMParser ) { // Standard
				tmp = new DOMParser();
				xml = tmp.parseFromString( data , "text/xml" );
			} else { // IE
				xml = new ActiveXObject( "Microsoft.XMLDOM" );
				xml.async = "false";
				xml.loadXML( data );
			}
		} catch( e ) {
			xml = undefined;
		}
		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
			jQuery.error( "Invalid XML: " + data );
		}
		return xml;
	},

	noop: function() {},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && jQuery.trim( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
	},

	// args is for internal usage only
	each: function( obj, callback, args ) {
		var value,
			i = 0,
			length = obj.length,
			isArray = isArraylike( obj );

		if ( args ) {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.apply( obj[ i ], args );

					if ( value === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}
		}

		return obj;
	},

	// Use native String.trim function wherever possible
	trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
		function( text ) {
			return text == null ?
				"" :
				core_trim.call( text );
		} :

		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				( text + "" ).replace( rtrim, "" );
		},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArraylike( Object(arr) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
					[ arr ] : arr
				);
			} else {
				core_push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		var len;

		if ( arr ) {
			if ( core_indexOf ) {
				return core_indexOf.call( arr, elem, i );
			}

			len = arr.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {
				// Skip accessing in sparse arrays
				if ( i in arr && arr[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var l = second.length,
			i = first.length,
			j = 0;

		if ( typeof l === "number" ) {
			for ( ; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}
		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, inv ) {
		var retVal,
			ret = [],
			i = 0,
			length = elems.length;
		inv = !!inv;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var value,
			i = 0,
			length = elems.length,
			isArray = isArraylike( elems ),
			ret = [];

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return core_concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		var args, proxy, tmp;

		if ( typeof context === "string" ) {
			tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		args = core_slice.call( arguments, 2 );
		proxy = function() {
			return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	},

	// Multifunctional method to get and set values of a collection
	// The value/s can optionally be executed if it's a function
	access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
		var i = 0,
			length = elems.length,
			bulk = key == null;

		// Sets many values
		if ( jQuery.type( key ) === "object" ) {
			chainable = true;
			for ( i in key ) {
				jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
			}

		// Sets one value
		} else if ( value !== undefined ) {
			chainable = true;

			if ( !jQuery.isFunction( value ) ) {
				raw = true;
			}

			if ( bulk ) {
				// Bulk operations run against the entire set
				if ( raw ) {
					fn.call( elems, value );
					fn = null;

				// ...except when executing function values
				} else {
					bulk = fn;
					fn = function( elem, key, value ) {
						return bulk.call( jQuery( elem ), value );
					};
				}
			}

			if ( fn ) {
				for ( ; i < length; i++ ) {
					fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
				}
			}
		}

		return chainable ?
			elems :

			// Gets
			bulk ?
				fn.call( elems ) :
				length ? fn( elems[0], key ) : emptyGet;
	},

	now: function() {
		return ( new Date() ).getTime();
	}
});

jQuery.ready.promise = function( obj ) {
	if ( !readyList ) {

		readyList = jQuery.Deferred();

		// Catch cases where $(document).ready() is called after the browser event has already occurred.
		// we once tried to use readyState "interactive" here, but it caused issues like the one
		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			setTimeout( jQuery.ready );

		// Standards-based browsers support DOMContentLoaded
		} else if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", completed, false );

		// If IE event model is used
		} else {
			// Ensure firing before onload, maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", completed );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", completed );

			// If IE and not a frame
			// continually check to see if the document is ready
			var top = false;

			try {
				top = window.frameElement == null && document.documentElement;
			} catch(e) {}

			if ( top && top.doScroll ) {
				(function doScrollCheck() {
					if ( !jQuery.isReady ) {

						try {
							// Use the trick by Diego Perini
							// http://javascript.nwbox.com/IEContentLoaded/
							top.doScroll("left");
						} catch(e) {
							return setTimeout( doScrollCheck, 50 );
						}

						// detach all dom ready events
						detach();

						// and execute any waiting functions
						jQuery.ready();
					}
				})();
			}
		}
	}
	return readyList.promise( obj );
};

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

function isArraylike( obj ) {
	var length = obj.length,
		type = jQuery.type( obj );

	if ( jQuery.isWindow( obj ) ) {
		return false;
	}

	if ( obj.nodeType === 1 && length ) {
		return true;
	}

	return type === "array" || type !== "function" &&
		( length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}

// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};

// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
	var object = optionsCache[ options ] = {};
	jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	});
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		( optionsCache[ options ] || createOptions( options ) ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,
		// Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list was already fired
		fired,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = !options.once && [],
		// Fire callbacks
		fire = function( data ) {
			memory = options.memory && data;
			fired = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			firing = true;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
					memory = false; // To prevent further calls using add
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( stack ) {
					if ( stack.length ) {
						fire( stack.shift() );
					}
				} else if ( memory ) {
					list = [];
				} else {
					self.disable();
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					// First, we save the current length
					var start = list.length;
					(function add( args ) {
						jQuery.each( args, function( _, arg ) {
							var type = jQuery.type( arg );
							if ( type === "function" ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && type !== "string" ) {
								// Inspect recursively
								add( arg );
							}
						});
					})( arguments );
					// Do we need to add the callbacks to the
					// current firing batch?
					if ( firing ) {
						firingLength = list.length;
					// With memory, if we're not firing then
					// we should call right away
					} else if ( memory ) {
						firingStart = start;
						fire( memory );
					}
				}
				return this;
			},
			// Remove a callback from the list
			remove: function() {
				if ( list ) {
					jQuery.each( arguments, function( _, arg ) {
						var index;
						while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
							list.splice( index, 1 );
							// Handle firing indexes
							if ( firing ) {
								if ( index <= firingLength ) {
									firingLength--;
								}
								if ( index <= firingIndex ) {
									firingIndex--;
								}
							}
						}
					});
				}
				return this;
			},
			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
			},
			// Remove all callbacks from the list
			empty: function() {
				list = [];
				return this;
			},
			// Have the list do nothing anymore
			disable: function() {
				list = stack = memory = undefined;
				return this;
			},
			// Is it disabled?
			disabled: function() {
				return !list;
			},
			// Lock the list in its current state
			lock: function() {
				stack = undefined;
				if ( !memory ) {
					self.disable();
				}
				return this;
			},
			// Is it locked?
			locked: function() {
				return !stack;
			},
			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				args = args || [];
				args = [ context, args.slice ? args.slice() : args ];
				if ( list && ( !fired || stack ) ) {
					if ( firing ) {
						stack.push( args );
					} else {
						fire( args );
					}
				}
				return this;
			},
			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},
			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};
jQuery.extend({

	Deferred: function( func ) {
		var tuples = [
				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks("memory") ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred(function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var action = tuple[ 0 ],
								fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[1] ](function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && jQuery.isFunction( returned.promise ) ) {
									returned.promise()
										.done( newDefer.resolve )
										.fail( newDefer.reject )
										.progress( newDefer.notify );
								} else {
									newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
								}
							});
						});
						fns = null;
					}).promise();
				},
				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[1] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(function() {
					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
			}

			// deferred[ resolve | reject | notify ]
			deferred[ tuple[0] ] = function() {
				deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
				return this;
			};
			deferred[ tuple[0] + "With" ] = list.fireWith;
		});

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = core_slice.call( arguments ),
			length = resolveValues.length,

			// the count of uncompleted subordinates
			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

			// Update function for both resolve and progress values
			updateFunc = function( i, contexts, values ) {
				return function( value ) {
					contexts[ i ] = this;
					values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
					if( values === progressValues ) {
						deferred.notifyWith( contexts, values );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( contexts, values );
					}
				};
			},

			progressValues, progressContexts, resolveContexts;

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			progressValues = new Array( length );
			progressContexts = new Array( length );
			resolveContexts = new Array( length );
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressContexts, progressValues ) );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( resolveContexts, resolveValues );
		}

		return deferred.promise();
	}
});
jQuery.support = (function() {

	var support, all, a,
		input, select, fragment,
		opt, eventName, isSupported, i,
		div = document.createElement("div");

	// Setup
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";

	// Support tests won't run in some limited or non-browser environments
	all = div.getElementsByTagName("*");
	a = div.getElementsByTagName("a")[ 0 ];
	if ( !all || !a || !all.length ) {
		return {};
	}

	// First batch of tests
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	a.style.cssText = "top:1px;float:left;opacity:.5";
	support = {
		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: div.firstChild.nodeType === 3,

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: a.getAttribute("href") === "/a",

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.5/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
		checkOn: !!input.value,

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Tests for enctype support on a form (#6743)
		enctype: !!document.createElement("form").enctype,

		// Makes sure cloning an html5 element does not cause problems
		// Where outerHTML is undefined, this still works
		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",

		// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
		boxModel: document.compatMode === "CSS1Compat",

		// Will be defined later
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true,
		boxSizingReliable: true,
		pixelPosition: false
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Support: IE<9
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	// Check if we can trust getAttribute("value")
	input = document.createElement("input");
	input.setAttribute( "value", "" );
	support.input = input.getAttribute( "value" ) === "";

	// Check if an input maintains its value after becoming a radio
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";

	// #11217 - WebKit loses check when the name is after the checked attribute
	input.setAttribute( "checked", "t" );
	input.setAttribute( "name", "t" );

	fragment = document.createDocumentFragment();
	fragment.appendChild( input );

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE<9
	// Opera does not clone events (and typeof div.attachEvent === undefined).
	// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
	if ( div.attachEvent ) {
		div.attachEvent( "onclick", function() {
			support.noCloneEvent = false;
		});

		div.cloneNode( true ).click();
	}

	// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
	// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
	for ( i in { submit: true, change: true, focusin: true }) {
		div.setAttribute( eventName = "on" + i, "t" );

		support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
	}

	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	// Run tests that need a body at doc ready
	jQuery(function() {
		var container, marginDiv, tds,
			divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
			body = document.getElementsByTagName("body")[0];

		if ( !body ) {
			// Return for frameset docs that don't have a body
			return;
		}

		container = document.createElement("div");
		container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";

		body.appendChild( container ).appendChild( div );

		// Support: IE8
		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
		tds = div.getElementsByTagName("td");
		tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
		isSupported = ( tds[ 0 ].offsetHeight === 0 );

		tds[ 0 ].style.display = "";
		tds[ 1 ].style.display = "none";

		// Support: IE8
		// Check if empty table cells still have offsetWidth/Height
		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

		// Check box-sizing and margin behavior
		div.innerHTML = "";
		div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
		support.boxSizing = ( div.offsetWidth === 4 );
		support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );

		// Use window.getComputedStyle because jsdom on node.js will break without it.
		if ( window.getComputedStyle ) {
			support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. (#3333)
			// Fails in WebKit before Feb 2011 nightlies
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			marginDiv = div.appendChild( document.createElement("div") );
			marginDiv.style.cssText = div.style.cssText = divReset;
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";

			support.reliableMarginRight =
				!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
		}

		if ( typeof div.style.zoom !== core_strundefined ) {
			// Support: IE<8
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			div.innerHTML = "";
			div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
			support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );

			// Support: IE6
			// Check if elements with layout shrink-wrap their children
			div.style.display = "block";
			div.innerHTML = "<div></div>";
			div.firstChild.style.width = "5px";
			support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );

			if ( support.inlineBlockNeedsLayout ) {
				// Prevent IE 6 from affecting layout for positioned elements #11048
				// Prevent IE from shrinking the body in IE 7 mode #12869
				// Support: IE<8
				body.style.zoom = 1;
			}
		}

		body.removeChild( container );

		// Null elements to avoid leaks in IE
		container = div = tds = marginDiv = null;
	});

	// Null elements to avoid leaks in IE
	all = select = fragment = opt = a = input = null;

	return support;
})();

var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
	rmultiDash = /([A-Z])/g;

function internalData( elem, name, data, pvt /* Internal Use Only */ ){
	if ( !jQuery.acceptData( elem ) ) {
		return;
	}

	var thisCache, ret,
		internalKey = jQuery.expando,
		getByName = typeof name === "string",

		// We have to handle DOM nodes and JS objects differently because IE6-7
		// can't GC object references properly across the DOM-JS boundary
		isNode = elem.nodeType,

		// Only DOM nodes need the global jQuery cache; JS object data is
		// attached directly to the object so GC can occur automatically
		cache = isNode ? jQuery.cache : elem,

		// Only defining an ID for JS objects if its cache already exists allows
		// the code to shortcut on the same path as a DOM node with no cache
		id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;

	// Avoid doing any more work than we need to when trying to get data on an
	// object that has no data at all
	if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
		return;
	}

	if ( !id ) {
		// Only DOM nodes need a new unique ID for each element since their data
		// ends up in the global cache
		if ( isNode ) {
			elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
		} else {
			id = internalKey;
		}
	}

	if ( !cache[ id ] ) {
		cache[ id ] = {};

		// Avoids exposing jQuery metadata on plain JS objects when the object
		// is serialized using JSON.stringify
		if ( !isNode ) {
			cache[ id ].toJSON = jQuery.noop;
		}
	}

	// An object can be passed to jQuery.data instead of a key/value pair; this gets
	// shallow copied over onto the existing cache
	if ( typeof name === "object" || typeof name === "function" ) {
		if ( pvt ) {
			cache[ id ] = jQuery.extend( cache[ id ], name );
		} else {
			cache[ id ].data = jQuery.extend( cache[ id ].data, name );
		}
	}

	thisCache = cache[ id ];

	// jQuery data() is stored in a separate object inside the object's internal data
	// cache in order to avoid key collisions between internal data and user-defined
	// data.
	if ( !pvt ) {
		if ( !thisCache.data ) {
			thisCache.data = {};
		}

		thisCache = thisCache.data;
	}

	if ( data !== undefined ) {
		thisCache[ jQuery.camelCase( name ) ] = data;
	}

	// Check for both converted-to-camel and non-converted data property names
	// If a data property was specified
	if ( getByName ) {

		// First Try to find as-is property data
		ret = thisCache[ name ];

		// Test for null|undefined property data
		if ( ret == null ) {

			// Try to find the camelCased property
			ret = thisCache[ jQuery.camelCase( name ) ];
		}
	} else {
		ret = thisCache;
	}

	return ret;
}

function internalRemoveData( elem, name, pvt ) {
	if ( !jQuery.acceptData( elem ) ) {
		return;
	}

	var i, l, thisCache,
		isNode = elem.nodeType,

		// See jQuery.data for more information
		cache = isNode ? jQuery.cache : elem,
		id = isNode ? elem[ jQuery.expando ] : jQuery.expando;

	// If there is already no cache entry for this object, there is no
	// purpose in continuing
	if ( !cache[ id ] ) {
		return;
	}

	if ( name ) {

		thisCache = pvt ? cache[ id ] : cache[ id ].data;

		if ( thisCache ) {

			// Support array or space separated string names for data keys
			if ( !jQuery.isArray( name ) ) {

				// try the string as a key before any manipulation
				if ( name in thisCache ) {
					name = [ name ];
				} else {

					// split the camel cased version by spaces unless a key with the spaces exists
					name = jQuery.camelCase( name );
					if ( name in thisCache ) {
						name = [ name ];
					} else {
						name = name.split(" ");
					}
				}
			} else {
				// If "name" is an array of keys...
				// When data is initially created, via ("key", "val") signature,
				// keys will be converted to camelCase.
				// Since there is no way to tell _how_ a key was added, remove
				// both plain key and camelCase key. #12786
				// This will only penalize the array argument path.
				name = name.concat( jQuery.map( name, jQuery.camelCase ) );
			}

			for ( i = 0, l = name.length; i < l; i++ ) {
				delete thisCache[ name[i] ];
			}

			// If there is no data left in the cache, we want to continue
			// and let the cache object itself get destroyed
			if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
				return;
			}
		}
	}

	// See jQuery.data for more information
	if ( !pvt ) {
		delete cache[ id ].data;

		// Don't destroy the parent cache unless the internal data object
		// had been the only thing left in it
		if ( !isEmptyDataObject( cache[ id ] ) ) {
			return;
		}
	}

	// Destroy the cache
	if ( isNode ) {
		jQuery.cleanData( [ elem ], true );

	// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
	} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
		delete cache[ id ];

	// When all else fails, null
	} else {
		cache[ id ] = null;
	}
}

jQuery.extend({
	cache: {},

	// Unique for each copy of jQuery on the page
	// Non-digits removed to match rinlinejQuery
	expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		// Ban all objects except for Flash (which handle expandos)
		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"applet": true
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data ) {
		return internalData( elem, name, data );
	},

	removeData: function( elem, name ) {
		return internalRemoveData( elem, name );
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return internalData( elem, name, data, true );
	},

	_removeData: function( elem, name ) {
		return internalRemoveData( elem, name, true );
	},

	// A method for determining if a DOM node can handle the data expando
	acceptData: function( elem ) {
		// Do not set data on non-element because it will not be cleared (#8335).
		if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
			return false;
		}

		var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];

		// nodes accept data unless otherwise specified; rejection can be conditional
		return !noData || noData !== true && elem.getAttribute("classid") === noData;
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		var attrs, name,
			elem = this[0],
			i = 0,
			data = null;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = jQuery.data( elem );

				if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
					attrs = elem.attributes;
					for ( ; i < attrs.length; i++ ) {
						name = attrs[i].name;

						if ( !name.indexOf( "data-" ) ) {
							name = jQuery.camelCase( name.slice(5) );

							dataAttr( elem, name, data[ name ] );
						}
					}
					jQuery._data( elem, "parsedAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		return jQuery.access( this, function( value ) {

			if ( value === undefined ) {
				// Try to fetch any internally stored data first
				return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
			}

			this.each(function() {
				jQuery.data( this, key, value );
			});
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});

function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {

		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();

		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
					data === "false" ? false :
					data === "null" ? null :
					// Only convert to a number if it doesn't change the string
					+data + "" === data ? +data :
					rbrace.test( data ) ? jQuery.parseJSON( data ) :
						data;
			} catch( e ) {}

			// Make sure we set the data so it isn't changed later
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
	var name;
	for ( name in obj ) {

		// if the public data object is empty, the private is still empty
		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
			continue;
		}
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}
jQuery.extend({
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = jQuery._data( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray(data) ) {
					queue = jQuery._data( elem, type, jQuery.makeArray(data) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		hooks.cur = fn;
		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// not intended for public consumption - generates a queueHooks object, or returns the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return jQuery._data( elem, key ) || jQuery._data( elem, key, {
			empty: jQuery.Callbacks("once memory").add(function() {
				jQuery._removeData( elem, type + "queue" );
				jQuery._removeData( elem, key );
			})
		});
	}
});

jQuery.fn.extend({
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[0], type );
		}

		return data === undefined ?
			this :
			this.each(function() {
				var queue = jQuery.queue( this, type, data );

				// ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[0] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},
	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
		type = type || "fx";

		return this.queue( type, function( next, hooks ) {
			var timeout = setTimeout( next, time );
			hooks.stop = function() {
				clearTimeout( timeout );
			};
		});
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},
	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while( i-- ) {
			tmp = jQuery._data( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
});
var nodeHook, boolHook,
	rclass = /[\t\r\n]/g,
	rreturn = /\r/g,
	rfocusable = /^(?:input|select|textarea|button|object)$/i,
	rclickable = /^(?:a|area)$/i,
	rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
	ruseDefault = /^(?:checked|selected)$/i,
	getSetAttribute = jQuery.support.getSetAttribute,
	getSetInput = jQuery.support.input;

jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each(function() {
			jQuery.removeAttr( this, name );
		});
	},

	prop: function( name, value ) {
		return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		name = jQuery.propFix[ name ] || name;
		return this.each(function() {
			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch( e ) {}
		});
	},

	addClass: function( value ) {
		var classes, elem, cur, clazz, j,
			i = 0,
			len = this.length,
			proceed = typeof value === "string" && value;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).addClass( value.call( this, j, this.className ) );
			});
		}

		if ( proceed ) {
			// The disjunction here is for better compressibility (see removeClass)
			classes = ( value || "" ).match( core_rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).replace( rclass, " " ) :
					" "
				);

				if ( cur ) {
					j = 0;
					while ( (clazz = classes[j++]) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}
					elem.className = jQuery.trim( cur );

				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, clazz, j,
			i = 0,
			len = this.length,
			proceed = arguments.length === 0 || typeof value === "string" && value;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).removeClass( value.call( this, j, this.className ) );
			});
		}
		if ( proceed ) {
			classes = ( value || "" ).match( core_rnotwhite ) || [];

			for ( ; i < len; i++ ) {
				elem = this[ i ];
				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( elem.className ?
					( " " + elem.className + " " ).replace( rclass, " " ) :
					""
				);

				if ( cur ) {
					j = 0;
					while ( (clazz = classes[j++]) ) {
						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}
					elem.className = value ? jQuery.trim( cur ) : "";
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( i ) {
				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					i = 0,
					self = jQuery( this ),
					state = stateVal,
					classNames = value.match( core_rnotwhite ) || [];

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space separated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			// Toggle whole class name
			} else if ( type === core_strundefined || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.className );
				}

				// If the element has a class name or if we're passed "false",
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ",
			i = 0,
			l = this.length;
		for ( ; i < l; i++ ) {
			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
				return true;
			}
		}

		return false;
	},

	val: function( value ) {
		var ret, hooks, isFunction,
			elem = this[0];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
					return ret;
				}

				ret = elem.value;

				return typeof ret === "string" ?
					// handle most common string cases
					ret.replace(rreturn, "") :
					// handle cases where value is null/undef or number
					ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each(function( i ) {
			var val,
				self = jQuery(this);

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, self.val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map(val, function ( value ) {
					return value == null ? "" : value + "";
				});
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				// attributes.value is undefined in Blackberry 4.7 but
				// uses .value. See #6932
				var val = elem.attributes.value;
				return !val || val.specified ? elem.value : elem.text;
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// oldIE doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&
							// Don't return options that are disabled or in a disabled optgroup
							( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var values = jQuery.makeArray( value );

				jQuery(elem).find("option").each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});

				if ( !values.length ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	},

	attr: function( elem, name, value ) {
		var hooks, notxml, ret,
			nType = elem.nodeType;

		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === core_strundefined ) {
			return jQuery.prop( elem, name, value );
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		// All attributes are lowercase
		// Grab necessary hook if one is defined
		if ( notxml ) {
			name = name.toLowerCase();
			hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {

			if ( value === null ) {
				jQuery.removeAttr( elem, name );

			} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				elem.setAttribute( name, value + "" );
				return value;
			}

		} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
			return ret;

		} else {

			// In IE9+, Flash objects don't have .getAttribute (#12945)
			// Support: IE9+
			if ( typeof elem.getAttribute !== core_strundefined ) {
				ret =  elem.getAttribute( name );
			}

			// Non-existent attributes return null, we normalize to undefined
			return ret == null ?
				undefined :
				ret;
		}
	},

	removeAttr: function( elem, value ) {
		var name, propName,
			i = 0,
			attrNames = value && value.match( core_rnotwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( (name = attrNames[i++]) ) {
				propName = jQuery.propFix[ name ] || name;

				// Boolean attributes get special treatment (#10870)
				if ( rboolean.test( name ) ) {
					// Set corresponding property to false for boolean attributes
					// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
					if ( !getSetAttribute && ruseDefault.test( name ) ) {
						elem[ jQuery.camelCase( "default-" + name ) ] =
							elem[ propName ] = false;
					} else {
						elem[ propName ] = false;
					}

				// See #9699 for explanation of this approach (setting first, then removal)
				} else {
					jQuery.attr( elem, name, "" );
				}

				elem.removeAttribute( getSetAttribute ? name : propName );
			}
		}
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
					// Setting the type on a radio button after the value resets the value in IE6-9
					// Reset value to default in case type is set after value during creation
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	propFix: {
		tabindex: "tabIndex",
		readonly: "readOnly",
		"for": "htmlFor",
		"class": "className",
		maxlength: "maxLength",
		cellspacing: "cellSpacing",
		cellpadding: "cellPadding",
		rowspan: "rowSpan",
		colspan: "colSpan",
		usemap: "useMap",
		frameborder: "frameBorder",
		contenteditable: "contentEditable"
	},

	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {
			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				return ( elem[ name ] = value );
			}

		} else {
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
				return ret;

			} else {
				return elem[ name ];
			}
		}
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				var attributeNode = elem.getAttributeNode("tabindex");

				return attributeNode && attributeNode.specified ?
					parseInt( attributeNode.value, 10 ) :
					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
						0 :
						undefined;
			}
		}
	}
});

// Hook for boolean attributes
boolHook = {
	get: function( elem, name ) {
		var
			// Use .prop to determine if this attribute is understood as boolean
			prop = jQuery.prop( elem, name ),

			// Fetch it accordingly
			attr = typeof prop === "boolean" && elem.getAttribute( name ),
			detail = typeof prop === "boolean" ?

				getSetInput && getSetAttribute ?
					attr != null :
					// oldIE fabricates an empty string for missing boolean attributes
					// and conflates checked/selected into attroperties
					ruseDefault.test( name ) ?
						elem[ jQuery.camelCase( "default-" + name ) ] :
						!!attr :

				// fetch an attribute node for properties not recognized as boolean
				elem.getAttributeNode( name );

		return detail && detail.value !== false ?
			name.toLowerCase() :
			undefined;
	},
	set: function( elem, value, name ) {
		if ( value === false ) {
			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
			// IE<8 needs the *property* name
			elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );

		// Use defaultChecked and defaultSelected for oldIE
		} else {
			elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
		}

		return name;
	}
};

// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
	jQuery.attrHooks.value = {
		get: function( elem, name ) {
			var ret = elem.getAttributeNode( name );
			return jQuery.nodeName( elem, "input" ) ?

				// Ignore the value *property* by using defaultValue
				elem.defaultValue :

				ret && ret.specified ? ret.value : undefined;
		},
		set: function( elem, value, name ) {
			if ( jQuery.nodeName( elem, "input" ) ) {
				// Does not return so that setAttribute is also used
				elem.defaultValue = value;
			} else {
				// Use nodeHook if defined (#1954); otherwise setAttribute is fine
				return nodeHook && nodeHook.set( elem, value, name );
			}
		}
	};
}

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

	// Use this for any attribute in IE6/7
	// This fixes almost every IE6/7 issue
	nodeHook = jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret = elem.getAttributeNode( name );
			return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
				ret.value :
				undefined;
		},
		set: function( elem, value, name ) {
			// Set the existing or create a new attribute node
			var ret = elem.getAttributeNode( name );
			if ( !ret ) {
				elem.setAttributeNode(
					(ret = elem.ownerDocument.createAttribute( name ))
				);
			}

			ret.value = value += "";

			// Break association with cloned elements by also using setAttribute (#9646)
			return name === "value" || value === elem.getAttribute( name ) ?
				value :
				undefined;
		}
	};

	// Set contenteditable to false on removals(#10429)
	// Setting to empty string throws an error as an invalid value
	jQuery.attrHooks.contenteditable = {
		get: nodeHook.get,
		set: function( elem, value, name ) {
			nodeHook.set( elem, value === "" ? false : value, name );
		}
	};

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each([ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		});
	});
}


// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			get: function( elem ) {
				var ret = elem.getAttribute( name, 2 );
				return ret == null ? undefined : ret;
			}
		});
	});

	// href/src property should get the full normalized URL (#10299/#12915)
	jQuery.each([ "href", "src" ], function( i, name ) {
		jQuery.propHooks[ name ] = {
			get: function( elem ) {
				return elem.getAttribute( name, 4 );
			}
		};
	});
}

if ( !jQuery.support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {
			// Return undefined in the case of empty string
			// Note: IE uppercases css property names, but if we were to .toLowerCase()
			// .cssText, that would destroy case senstitivity in URL's, like in "background"
			return elem.style.cssText || undefined;
		},
		set: function( elem, value ) {
			return ( elem.style.cssText = value + "" );
		}
	};
}

// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
			return null;
		}
	});
}

// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
	jQuery.propFix.enctype = "encoding";
}

// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
	jQuery.each([ "radio", "checkbox" ], function() {
		jQuery.valHooks[ this ] = {
			get: function( elem ) {
				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				return elem.getAttribute("value") === null ? "on" : elem.value;
			}
		};
	});
}
jQuery.each([ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
			}
		}
	});
});
var rformElems = /^(?:input|select|textarea)$/i,
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|contextmenu)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {
		var tmp, events, t, handleObjIn,
			special, eventHandle, handleObj,
			handlers, type, namespaces, origType,
			elemData = jQuery._data( elem );

		// Don't attach events to noData or text/comment nodes (but allow plain objects)
		if ( !elemData ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !(events = elemData.events) ) {
			events = elemData.events = {};
		}
		if ( !(eventHandle = elemData.handle) ) {
			eventHandle = elemData.handle = function( e ) {
				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};
			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
			eventHandle.elem = elem;
		}

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = ( types || "" ).match( core_rnotwhite ) || [""];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[t] ) || [];
			type = origType = tmp[1];
			namespaces = ( tmp[2] || "" ).split( "." ).sort();

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend({
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join(".")
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !(handlers = events[ type ]) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener/attachEvent if the special events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {
		var j, handleObj, tmp,
			origCount, t, events,
			special, handlers, type,
			namespaces, origType,
			elemData = jQuery.hasData( elem ) && jQuery._data( elem );

		if ( !elemData || !(events = elemData.events) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( core_rnotwhite ) || [""];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[t] ) || [];
			type = origType = tmp[1];
			namespaces = ( tmp[2] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					( !handler || handler.guid === handleObj.guid ) &&
					( !tmp || tmp.test( handleObj.namespace ) ) &&
					( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			delete elemData.handle;

			// removeData also checks for emptiness and clears the expando if empty
			// so use it instead of delete
			jQuery._removeData( elem, "events" );
		}
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		var handle, ontype, cur,
			bubbleType, special, tmp, i,
			eventPath = [ elem || document ],
			type = core_hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];

		cur = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf(".") >= 0 ) {
			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split(".");
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf(":") < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		event.isTrigger = true;
		event.namespace = namespaces.join(".");
		event.namespace_re = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === (elem.ownerDocument || document) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {

			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
				event.preventDefault();
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name name as the event.
				// Can't use an .isFunction() check here because IE6/7 fails that test.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					try {
						elem[ type ]();
					} catch ( e ) {
						// IE<9 dies on focus/blur to hidden element (#1486,#12518)
						// only reproducible on winXP IE8 native, not IE9 in IE8 mode
					}
					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	dispatch: function( event ) {

		// Make a writable jQuery.Event from the native event object
		event = jQuery.event.fix( event );

		var i, ret, handleObj, matched, j,
			handlerQueue = [],
			args = core_slice.call( arguments ),
			handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[0] = event;
		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {

				// Triggered event must either 1) have no namespace, or
				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
				if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
							.apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( (event.result = ret) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var sel, handleObj, matches, i,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		// Black-hole SVG <use> instance trees (#13180)
		// Avoid non-left-click bubbling in Firefox (#3861)
		if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {

			for ( ; cur != this; cur = cur.parentNode || this ) {

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
					matches = [];
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matches[ sel ] === undefined ) {
							matches[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) >= 0 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matches[ sel ] ) {
							matches.push( handleObj );
						}
					}
					if ( matches.length ) {
						handlerQueue.push({ elem: cur, handlers: matches });
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		if ( delegateCount < handlers.length ) {
			handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
		}

		return handlerQueue;
	},

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// Create a writable copy of the event object and normalize some properties
		var i, prop, copy,
			type = event.type,
			originalEvent = event,
			fixHook = this.fixHooks[ type ];

		if ( !fixHook ) {
			this.fixHooks[ type ] = fixHook =
				rmouseEvent.test( type ) ? this.mouseHooks :
				rkeyEvent.test( type ) ? this.keyHooks :
				{};
		}
		copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;

		event = new jQuery.Event( originalEvent );

		i = copy.length;
		while ( i-- ) {
			prop = copy[ i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Support: IE<9
		// Fix target property (#1925)
		if ( !event.target ) {
			event.target = originalEvent.srcElement || document;
		}

		// Support: Chrome 23+, Safari?
		// Target should not be a text node (#504, #13143)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// Support: IE<9
		// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
		event.metaKey = !!event.metaKey;

		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
	},

	// Includes some event props shared by KeyEvent and MouseEvent
	props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),

	fixHooks: {},

	keyHooks: {
		props: "char charCode key keyCode".split(" "),
		filter: function( event, original ) {

			// Add which for key events
			if ( event.which == null ) {
				event.which = original.charCode != null ? original.charCode : original.keyCode;
			}

			return event;
		}
	},

	mouseHooks: {
		props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
		filter: function( event, original ) {
			var body, eventDoc, doc,
				button = original.button,
				fromElement = original.fromElement;

			// Calculate pageX/Y if missing and clientX/Y available
			if ( event.pageX == null && original.clientX != null ) {
				eventDoc = event.target.ownerDocument || document;
				doc = eventDoc.documentElement;
				body = eventDoc.body;

				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
			}

			// Add relatedTarget, if necessary
			if ( !event.relatedTarget && fromElement ) {
				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			// Note: button is not normalized, so don't use it
			if ( !event.which && button !== undefined ) {
				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
			}

			return event;
		}
	},

	special: {
		load: {
			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		click: {
			// For checkbox, fire native event so checked state will be right
			trigger: function() {
				if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
					this.click();
					return false;
				}
			}
		},
		focus: {
			// Fire native event if possible so blur/focus sequence is correct
			trigger: function() {
				if ( this !== document.activeElement && this.focus ) {
					try {
						this.focus();
						return false;
					} catch ( e ) {
						// Support: IE<9
						// If we error on focus to hidden element (#1486, #12518),
						// let .trigger() run the handlers
					}
				}
			},
			delegateType: "focusin"
		},
		blur: {
			trigger: function() {
				if ( this === document.activeElement && this.blur ) {
					this.blur();
					return false;
				}
			},
			delegateType: "focusout"
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Even when returnValue equals to undefined Firefox will still show alert
				if ( event.result !== undefined ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	},

	simulate: function( type, elem, event, bubble ) {
		// Piggyback on a donor event to simulate a different one.
		// Fake originalEvent to avoid donor's stopPropagation, but if the
		// simulated event prevents default then we do the same on the donor.
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{ type: type,
				isSimulated: true,
				originalEvent: {}
			}
		);
		if ( bubble ) {
			jQuery.event.trigger( e, null, elem );
		} else {
			jQuery.event.dispatch.call( elem, e );
		}
		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		var name = "on" + type;

		if ( elem.detachEvent ) {

			// #8545, #7054, preventing memory leaks for custom events in IE6-8
			// detachEvent needed property on element, by name of that event, to properly expose it to GC
			if ( typeof elem[ name ] === core_strundefined ) {
				elem[ name ] = null;
			}

			elem.detachEvent( name, handle );
		}
	};

jQuery.Event = function( src, props ) {
	// Allow instantiation without the 'new' keyword
	if ( !(this instanceof jQuery.Event) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
			src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;
		if ( !e ) {
			return;
		}

		// If preventDefault exists, run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// Support: IE
		// Otherwise set the returnValue property of the original event to false
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;
		if ( !e ) {
			return;
		}
		// If stopPropagation exists, run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}

		// Support: IE
		// Set the cancelBubble property of the original event to true
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	}
};

// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mousenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
});

// IE submit delegation
if ( !jQuery.support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Lazy-add a submit handler when a descendant form may potentially be submitted
			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
				// Node name check avoids a VML-related crash in IE (#9807)
				var elem = e.target,
					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
				if ( form && !jQuery._data( form, "submitBubbles" ) ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						event._submit_bubble = true;
					});
					jQuery._data( form, "submitBubbles", true );
				}
			});
			// return undefined since we don't need an event listener
		},

		postDispatch: function( event ) {
			// If form was submitted by the user, bubble the event up the tree
			if ( event._submit_bubble ) {
				delete event._submit_bubble;
				if ( this.parentNode && !event.isTrigger ) {
					jQuery.event.simulate( "submit", this.parentNode, event, true );
				}
			}
		},

		teardown: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
			jQuery.event.remove( this, "._submit" );
		}
	};
}

// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {

	jQuery.event.special.change = {

		setup: function() {

			if ( rformElems.test( this.nodeName ) ) {
				// IE doesn't fire change on a check/radio until blur; trigger it on click
				// after a propertychange. Eat the blur-change in special.change.handle.
				// This still fires onchange a second time for check/radio after blur.
				if ( this.type === "checkbox" || this.type === "radio" ) {
					jQuery.event.add( this, "propertychange._change", function( event ) {
						if ( event.originalEvent.propertyName === "checked" ) {
							this._just_changed = true;
						}
					});
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._just_changed && !event.isTrigger ) {
							this._just_changed = false;
						}
						// Allow triggered, simulated change events (#11500)
						jQuery.event.simulate( "change", this, event, true );
					});
				}
				return false;
			}
			// Delegated event; lazy-add a change handler on descendant inputs
			jQuery.event.add( this, "beforeactivate._change", function( e ) {
				var elem = e.target;

				if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event, true );
						}
					});
					jQuery._data( elem, "changeBubbles", true );
				}
			});
		},

		handle: function( event ) {
			var elem = event.target;

			// Swallow native change events from checkbox/radio, we already triggered them above
			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
				return event.handleObj.handler.apply( this, arguments );
			}
		},

		teardown: function() {
			jQuery.event.remove( this, "._change" );

			return !rformElems.test( this.nodeName );
		}
	};
}

// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler while someone wants focusin/focusout
		var attaches = 0,
			handler = function( event ) {
				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
			};

		jQuery.event.special[ fix ] = {
			setup: function() {
				if ( attaches++ === 0 ) {
					document.addEventListener( orig, handler, true );
				}
			},
			teardown: function() {
				if ( --attaches === 0 ) {
					document.removeEventListener( orig, handler, true );
				}
			}
		};
	});
}

jQuery.fn.extend({

	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
		var type, origFn;

		// Types can be a map of types/handlers
		if ( typeof types === "object" ) {
			// ( types-Object, selector, data )
			if ( typeof selector !== "string" ) {
				// ( types-Object, data )
				data = data || selector;
				selector = undefined;
			}
			for ( type in types ) {
				this.on( type, selector, data, types[ type ], one );
			}
			return this;
		}

		if ( data == null && fn == null ) {
			// ( types, fn )
			fn = selector;
			data = selector = undefined;
		} else if ( fn == null ) {
			if ( typeof selector === "string" ) {
				// ( types, selector, fn )
				fn = data;
				data = undefined;
			} else {
				// ( types, data, fn )
				fn = data;
				data = selector;
				selector = undefined;
			}
		}
		if ( fn === false ) {
			fn = returnFalse;
		} else if ( !fn ) {
			return this;
		}

		if ( one === 1 ) {
			origFn = fn;
			fn = function( event ) {
				// Can use an empty set, since event contains the info
				jQuery().off( event );
				return origFn.apply( this, arguments );
			};
			// Use same guid so caller can remove using origFn
			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
		}
		return this.each( function() {
			jQuery.event.add( this, types, fn, data, selector );
		});
	},
	one: function( types, selector, data, fn ) {
		return this.on( types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {
			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {
			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {
			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each(function() {
			jQuery.event.remove( this, types, fn, selector );
		});
	},

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {
		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
	},

	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},
	triggerHandler: function( type, data ) {
		var elem = this[0];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
});
/*!
 * Sizzle CSS Selector Engine
 * Copyright 2012 jQuery Foundation and other contributors
 * Released under the MIT license
 * http://sizzlejs.com/
 */
(function( window, undefined ) {

var i,
	cachedruns,
	Expr,
	getText,
	isXML,
	compile,
	hasDuplicate,
	outermostContext,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsXML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,
	sortOrder,

	// Instance-specific data
	expando = "sizzle" + -(new Date()),
	preferredDoc = window.document,
	support = {},
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),

	// General-purpose constants
	strundefined = typeof undefined,
	MAX_NEGATIVE = 1 << 31,

	// Array methods
	arr = [],
	pop = arr.pop,
	push = arr.push,
	slice = arr.slice,
	// Use a stripped-down indexOf if we can't use a native one
	indexOf = arr.indexOf || function( elem ) {
		var i = 0,
			len = this.length;
		for ( ; i < len; i++ ) {
			if ( this[i] === elem ) {
				return i;
			}
		}
		return -1;
	},


	// Regular expressions

	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",
	// http://www.w3.org/TR/css3-syntax/#characters
	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",

	// Loosely modeled on CSS identifier characters
	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = characterEncoding.replace( "w", "w#" ),

	// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
	operators = "([*^$|!~]?=)",
	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
		"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",

	// Prefer arguments quoted,
	//   then not containing pseudos/brackets,
	//   then attribute selectors/non-parenthetical expressions,
	//   then anything else
	// These preferences are here to reduce the number of selectors
	//   needing tokenize in the PSEUDO preFilter
	pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + characterEncoding + ")" ),
		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
		"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rsibling = /[\x20\t\r\n\f]*[+~]/,

	rnative = /^[^{]+\{\s*\[native code/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rescape = /'|\\/g,
	rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,

	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
	funescape = function( _, escaped ) {
		var high = "0x" + escaped - 0x10000;
		// NaN means non-codepoint
		return high !== high ?
			escaped :
			// BMP codepoint
			high < 0 ?
				String.fromCharCode( high + 0x10000 ) :
				// Supplemental Plane codepoint (surrogate pair)
				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	};

// Use a stripped-down slice if we can't use a native one
try {
	slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
	slice = function( i ) {
		var elem,
			results = [];
		while ( (elem = this[i++]) ) {
			results.push( elem );
		}
		return results;
	};
}

/**
 * For feature detection
 * @param {Function} fn The function to test for native support
 */
function isNative( fn ) {
	return rnative.test( fn + "" );
}

/**
 * Create key-value caches of limited size
 * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var cache,
		keys = [];

	return (cache = function( key, value ) {
		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key += " " ) > Expr.cacheLength ) {
			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return (cache[ key ] = value);
	});
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created div and expects a boolean result
 */
function assert( fn ) {
	var div = document.createElement("div");

	try {
		return fn( div );
	} catch (e) {
		return false;
	} finally {
		// release memory in IE
		div = null;
	}
}

function Sizzle( selector, context, results, seed ) {
	var match, elem, m, nodeType,
		// QSA vars
		i, groups, old, nid, newContext, newSelector;

	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
		setDocument( context );
	}

	context = context || document;
	results = results || [];

	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
		return [];
	}

	if ( !documentIsXML && !seed ) {

		// Shortcuts
		if ( (match = rquickExpr.exec( selector )) ) {
			// Speed-up: Sizzle("#ID")
			if ( (m = match[1]) ) {
				if ( nodeType === 9 ) {
					elem = context.getElementById( m );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE, Opera, and Webkit return items
						// by name instead of ID
						if ( elem.id === m ) {
							results.push( elem );
							return results;
						}
					} else {
						return results;
					}
				} else {
					// Context is not a document
					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
						contains( context, elem ) && elem.id === m ) {
						results.push( elem );
						return results;
					}
				}

			// Speed-up: Sizzle("TAG")
			} else if ( match[2] ) {
				push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
				return results;

			// Speed-up: Sizzle(".CLASS")
			} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
				push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
				return results;
			}
		}

		// QSA path
		if ( support.qsa && !rbuggyQSA.test(selector) ) {
			old = true;
			nid = expando;
			newContext = context;
			newSelector = nodeType === 9 && selector;

			// qSA works strangely on Element-rooted queries
			// We can work around this by specifying an extra ID on the root
			// and working up from there (Thanks to Andrew Dupont for the technique)
			// IE 8 doesn't work on object elements
			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
				groups = tokenize( selector );

				if ( (old = context.getAttribute("id")) ) {
					nid = old.replace( rescape, "\\$&" );
				} else {
					context.setAttribute( "id", nid );
				}
				nid = "[id='" + nid + "'] ";

				i = groups.length;
				while ( i-- ) {
					groups[i] = nid + toSelector( groups[i] );
				}
				newContext = rsibling.test( selector ) && context.parentNode || context;
				newSelector = groups.join(",");
			}

			if ( newSelector ) {
				try {
					push.apply( results, slice.call( newContext.querySelectorAll(
						newSelector
					), 0 ) );
					return results;
				} catch(qsaError) {
				} finally {
					if ( !old ) {
						context.removeAttribute("id");
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Detect xml
 * @param {Element|Object} elem An element or a document
 */
isXML = Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var doc = node ? node.ownerDocument || node : preferredDoc;

	// If no document and documentElement is available, return
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Set our document
	document = doc;
	docElem = doc.documentElement;

	// Support tests
	documentIsXML = isXML( doc );

	// Check if getElementsByTagName("*") returns only elements
	support.tagNameNoComments = assert(function( div ) {
		div.appendChild( doc.createComment("") );
		return !div.getElementsByTagName("*").length;
	});

	// Check if attributes should be retrieved by attribute nodes
	support.attributes = assert(function( div ) {
		div.innerHTML = "<select></select>";
		var type = typeof div.lastChild.getAttribute("multiple");
		// IE8 returns a string for some attributes even when not present
		return type !== "boolean" && type !== "string";
	});

	// Check if getElementsByClassName can be trusted
	support.getByClassName = assert(function( div ) {
		// Opera can't find a second classname (in 9.6)
		div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
		if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
			return false;
		}

		// Safari 3.2 caches class attributes and doesn't catch changes
		div.lastChild.className = "e";
		return div.getElementsByClassName("e").length === 2;
	});

	// Check if getElementById returns elements by name
	// Check if getElementsByName privileges form controls or returns elements by ID
	support.getByName = assert(function( div ) {
		// Inject content
		div.id = expando + 0;
		div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
		docElem.insertBefore( div, docElem.firstChild );

		// Test
		var pass = doc.getElementsByName &&
			// buggy browsers will return fewer than the correct 2
			doc.getElementsByName( expando ).length === 2 +
			// buggy browsers will return more than the correct 0
			doc.getElementsByName( expando + 0 ).length;
		support.getIdNotName = !doc.getElementById( expando );

		// Cleanup
		docElem.removeChild( div );

		return pass;
	});

	// IE6/7 return modified attributes
	Expr.attrHandle = assert(function( div ) {
		div.innerHTML = "<a href='#'></a>";
		return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
			div.firstChild.getAttribute("href") === "#";
	}) ?
		{} :
		{
			"href": function( elem ) {
				return elem.getAttribute( "href", 2 );
			},
			"type": function( elem ) {
				return elem.getAttribute("type");
			}
		};

	// ID find and filter
	if ( support.getIdNotName ) {
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
				var m = context.getElementById( id );
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [m] : [];
			}
		};
		Expr.filter["ID"] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute("id") === attrId;
			};
		};
	} else {
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
				var m = context.getElementById( id );

				return m ?
					m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
						[m] :
						undefined :
					[];
			}
		};
		Expr.filter["ID"] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
				return node && node.value === attrId;
			};
		};
	}

	// Tag
	Expr.find["TAG"] = support.tagNameNoComments ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== strundefined ) {
				return context.getElementsByTagName( tag );
			}
		} :
		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( (elem = results[i++]) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Name
	Expr.find["NAME"] = support.getByName && function( tag, context ) {
		if ( typeof context.getElementsByName !== strundefined ) {
			return context.getElementsByName( name );
		}
	};

	// Class
	Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
			return context.getElementsByClassName( className );
		}
	};

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21),
	// no need to also add to buggyMatches since matches checks buggyQSA
	// A support test would require too much code (would include document ready)
	rbuggyQSA = [ ":focus" ];

	if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert(function( div ) {
			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explictly
			// setting a boolean content attribute,
			// since its presence should be enough
			// http://bugs.jquery.com/ticket/12359
			div.innerHTML = "<select><option selected=''></option></select>";

			// IE8 - Some boolean attributes are not treated correctly
			if ( !div.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":checked").length ) {
				rbuggyQSA.push(":checked");
			}
		});

		assert(function( div ) {

			// Opera 10-12/IE8 - ^= $= *= and empty values
			// Should not select anything
			div.innerHTML = "<input type='hidden' i=''/>";
			if ( div.querySelectorAll("[i^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":enabled").length ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Opera 10-11 does not throw on post-comma invalid pseudos
			div.querySelectorAll("*,:x");
			rbuggyQSA.push(",.*:");
		});
	}

	if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.webkitMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector) )) ) {

		assert(function( div ) {
			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( div, "div" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( div, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		});
	}

	rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
	rbuggyMatches = new RegExp( rbuggyMatches.join("|") );

	// Element contains another
	// Purposefully does not implement inclusive descendent
	// As in, an element does not contain itself
	contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b && b.parentNode;
			return a === bup || !!( bup && bup.nodeType === 1 && (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
			));
		} :
		function( a, b ) {
			if ( b ) {
				while ( (b = b.parentNode) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	// Document order sorting
	sortOrder = docElem.compareDocumentPosition ?
	function( a, b ) {
		var compare;

		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
			if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
				if ( a === doc || contains( preferredDoc, a ) ) {
					return -1;
				}
				if ( b === doc || contains( preferredDoc, b ) ) {
					return 1;
				}
				return 0;
			}
			return compare & 4 ? -1 : 1;
		}

		return a.compareDocumentPosition ? -1 : 1;
	} :
	function( a, b ) {
		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;

		// Parentless nodes are either documents or disconnected
		} else if ( !aup || !bup ) {
			return a === doc ? -1 :
				b === doc ? 1 :
				aup ? -1 :
				bup ? 1 :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( (cur = cur.parentNode) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( (cur = cur.parentNode) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[i] === bp[i] ) {
			i++;
		}

		return i ?
			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[i], bp[i] ) :

			// Otherwise nodes in our document sort first
			ap[i] === preferredDoc ? -1 :
			bp[i] === preferredDoc ? 1 :
			0;
	};

	// Always assume the presence of duplicates if sort doesn't
	// pass them to our comparison function (as in Google Chrome).
	hasDuplicate = false;
	[0, 0].sort( sortOrder );
	support.detectDuplicates = hasDuplicate;

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	// Make sure that attribute selectors are quoted
	expr = expr.replace( rattributeQuotes, "='$1']" );

	// rbuggyQSA always contains :focus, so no need for an existence check
	if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||
					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch(e) {}
	}

	return Sizzle( expr, document, null, [elem] ).length > 0;
};

Sizzle.contains = function( context, elem ) {
	// Set document vars if needed
	if ( ( context.ownerDocument || context ) !== document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {
	var val;

	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	if ( !documentIsXML ) {
		name = name.toLowerCase();
	}
	if ( (val = Expr.attrHandle[ name ]) ) {
		return val( elem );
	}
	if ( documentIsXML || support.attributes ) {
		return elem.getAttribute( name );
	}
	return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
		name :
		val && val.specified ? val.value : null;
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		i = 1,
		j = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		for ( ; (elem = results[i]); i++ ) {
			if ( elem === results[ i - 1 ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	return results;
};

function siblingCheck( a, b ) {
	var cur = b && a,
		diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( (cur = cur.nextSibling) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return (name === "input" || name === "button") && elem.type === type;
	};
}

// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
	return markFunction(function( argument ) {
		argument = +argument;
		return markFunction(function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ (j = matchIndexes[i]) ] ) {
					seed[j] = !(matches[j] = seed[j]);
				}
			}
		});
	});
}

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {
		// If no nodeType, this is expected to be an array
		for ( ; (node = elem[i]); i++ ) {
			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
		// Use textContent for elements
		// innerText usage removed for consistency of new lines (see #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {
			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}
	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[1] = match[1].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );

			if ( match[2] === "~=" ) {
				match[3] = " " + match[3] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {
			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[1] = match[1].toLowerCase();

			if ( match[1].slice( 0, 3 ) === "nth" ) {
				// nth-* requires argument
				if ( !match[3] ) {
					Sizzle.error( match[0] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );

			// other types prohibit arguments
			} else if ( match[3] ) {
				Sizzle.error( match[0] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[5] && match[2];

			if ( matchExpr["CHILD"].test( match[0] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[4] ) {
				match[2] = match[4];

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&
				// Get excess from tokenize (recursively)
				(excess = tokenize( unquoted, true )) &&
				// advance to the next closing parenthesis
				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {

				// excess is a negative index
				match[0] = match[0].slice( 0, excess );
				match[2] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeName ) {
			if ( nodeName === "*" ) {
				return function() { return true; };
			}

			nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
			};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
				classCache( className, function( elem ) {
					return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
				});
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
			};
		},

		"CHILD": function( type, what, argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, context, xml ) {
					var cache, outerCache, node, diff, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( (node = node[ dir ]) ) {
									if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
										return false;
									}
								}
								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {
							// Seek `elem` from a previously-cached index
							outerCache = parent[ expando ] || (parent[ expando ] = {});
							cache = outerCache[ type ] || [];
							nodeIndex = cache[0] === dirruns && cache[1];
							diff = cache[0] === dirruns && cache[2];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( (node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								(diff = nodeIndex = 0) || start.pop()) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						// Use previously-cached element index if available
						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
							diff = cache[1];

						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
						} else {
							// Use the same loop as above to seek `elem` from the start
							while ( (node = ++nodeIndex && node && node[ dir ] ||
								(diff = nodeIndex = 0) || start.pop()) ) {

								if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
									// Cache the index of each encountered element
									if ( useCache ) {
										(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
									}

									if ( node === elem ) {
										break;
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {
			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction(function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf.call( seed, matched[i] );
							seed[ idx ] = !( matches[ idx ] = matched[i] );
						}
					}) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {
		// Potentially complex pseudos
		"not": markFunction(function( selector ) {
			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction(function( seed, matches, context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( (elem = unmatched[i]) ) {
							seed[i] = !(matches[i] = elem);
						}
					}
				}) :
				function( elem, context, xml ) {
					input[0] = elem;
					matcher( input, null, xml, results );
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			return function( elem ) {
				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
			};
		}),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {
			// lang value must be a valid identifider
			if ( !ridentifier.test(lang || "") ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( (elemLang = documentIsXML ?
						elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
						elem.lang) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
				return false;
			};
		}),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
		},

		// Boolean properties
		"enabled": function( elem ) {
			return elem.disabled === false;
		},

		"disabled": function( elem ) {
			return elem.disabled === true;
		},

		"checked": function( elem ) {
			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
		},

		"selected": function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {
			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
			//   not comment, processing instructions, or others
			// Thanks to Diego Perini for the nodeName shortcut
			//   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos["empty"]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
			// use getAttribute instead to test this case
			return elem.nodeName.toLowerCase() === "input" &&
				elem.type === "text" &&
				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
		},

		// Position-in-collection
		"first": createPositionalPseudo(function() {
			return [ 0 ];
		}),

		"last": createPositionalPseudo(function( matchIndexes, length ) {
			return [ length - 1 ];
		}),

		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		}),

		"even": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"odd": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		})
	}
};

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

function tokenize( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || (match = rcomma.exec( soFar )) ) {
			if ( match ) {
				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[0].length ) || soFar;
			}
			groups.push( tokens = [] );
		}

		matched = false;

		// Combinators
		if ( (match = rcombinators.exec( soFar )) ) {
			matched = match.shift();
			tokens.push( {
				value: matched,
				// Cast descendant combinators to space
				type: match[0].replace( rtrim, " " )
			} );
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
				(match = preFilters[ type ]( match ))) ) {
				matched = match.shift();
				tokens.push( {
					value: matched,
					type: type,
					matches: match
				} );
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :
			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
}

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[i].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		checkNonElements = base && dir === "parentNode",
		doneName = done++;

	return combinator.first ?
		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( (elem = elem[ dir ]) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var data, cache, outerCache,
				dirkey = dirruns + " " + doneName;

			// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
			if ( xml ) {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || (elem[ expando ] = {});
						if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
							if ( (data = cache[1]) === true || data === cachedruns ) {
								return data === true;
							}
						} else {
							cache = outerCache[ dir ] = [ dirkey ];
							cache[1] = matcher( elem, context, xml ) || cachedruns;
							if ( cache[1] === true ) {
								return true;
							}
						}
					}
				}
			}
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[i]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[0];
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( (elem = unmatched[i]) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction(function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( (elem = temp[i]) ) {
					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {
					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( (elem = matcherOut[i]) ) {
							// Restore matcherIn since elem is not yet a final match
							temp.push( (matcherIn[i] = elem) );
						}
					}
					postFinder( null, (matcherOut = []), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( (elem = matcherOut[i]) &&
						(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {

						seed[temp] = !(results[temp] = elem);
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	});
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[0].type ],
		implicitRelative = leadingRelative || Expr.relative[" "],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf.call( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
		} ];

	for ( ; i < len; i++ ) {
		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
		} else {
			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {
				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[j].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	// A counter to specify which element is currently being matched
	var matcherCachedRuns = 0,
		bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, expandContext ) {
			var elem, j, matcher,
				setMatched = [],
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				outermost = expandContext != null,
				contextBackup = outermostContext,
				// We must always have either seed elements or context
				elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);

			if ( outermost ) {
				outermostContext = context !== document && context;
				cachedruns = matcherCachedRuns;
			}

			// Add elements passing elementMatchers directly to results
			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
			for ( ; (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context, xml ) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
						cachedruns = ++matcherCachedRuns;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// Apply set filters to unmatched elements
			matchedCount += i;
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( (matcher = setMatchers[j++]) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !group ) {
			group = tokenize( selector );
		}
		i = group.length;
		while ( i-- ) {
			cached = matcherFromTokens( group[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
	}
	return cached;
};

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[i], results );
	}
	return results;
}

function select( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		match = tokenize( selector );

	if ( !seed ) {
		// Try to minimize operations if there is only one group
		if ( match.length === 1 ) {

			// Take a shortcut and set the context if the root selector is an ID
			tokens = match[0] = match[0].slice( 0 );
			if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
					context.nodeType === 9 && !documentIsXML &&
					Expr.relative[ tokens[1].type ] ) {

				context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
				if ( !context ) {
					return results;
				}

				selector = selector.slice( tokens.shift().value.length );
			}

			// Fetch a seed set for right-to-left matching
			i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
			while ( i-- ) {
				token = tokens[i];

				// Abort if we hit a combinator
				if ( Expr.relative[ (type = token.type) ] ) {
					break;
				}
				if ( (find = Expr.find[ type ]) ) {
					// Search, expanding context for leading sibling combinators
					if ( (seed = find(
						token.matches[0].replace( runescape, funescape ),
						rsibling.test( tokens[0].type ) && context.parentNode || context
					)) ) {

						// If seed is empty or no tokens remain, we can return early
						tokens.splice( i, 1 );
						selector = seed.length && toSelector( tokens );
						if ( !selector ) {
							push.apply( results, slice.call( seed, 0 ) );
							return results;
						}

						break;
					}
				}
			}
		}
	}

	// Compile and execute a filtering function
	// Provide `match` to avoid retokenization if we modified the selector above
	compile( selector, match )(
		seed,
		context,
		documentIsXML,
		results,
		rsibling.test( selector )
	);
	return results;
}

// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];

// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();

// Initialize with the default document
setDocument();

// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;


})( window );
var runtil = /Until$/,
	rparentsprev = /^(?:parents|prev(?:Until|All))/,
	isSimple = /^.[^:#\[\.,]*$/,
	rneedsContext = jQuery.expr.match.needsContext,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var i, ret, self,
			len = this.length;

		if ( typeof selector !== "string" ) {
			self = this;
			return this.pushStack( jQuery( selector ).filter(function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			}) );
		}

		ret = [];
		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, this[ i ], ret );
		}

		// Needed because $( selector, context ) becomes $( context ).find( selector )
		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
		ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
		return ret;
	},

	has: function( target ) {
		var i,
			targets = jQuery( target, this ),
			len = targets.length;

		return this.filter(function() {
			for ( i = 0; i < len; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false) );
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true) );
	},

	is: function( selector ) {
		return !!selector && (
			typeof selector === "string" ?
				// If this is a positional/relative selector, check membership in the returned set
				// so $("p:first").is("p:last") won't return true for a doc with two "p".
				rneedsContext.test( selector ) ?
					jQuery( selector, this.context ).index( this[0] ) >= 0 :
					jQuery.filter( selector, this ).length > 0 :
				this.filter( selector ).length > 0 );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			ret = [],
			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			cur = this[i];

			while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
					ret.push( cur );
					break;
				}
				cur = cur.parentNode;
			}
		}

		return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return jQuery.inArray( this[0], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( jQuery.unique(all) );
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter(selector)
		);
	}
});

jQuery.fn.andSelf = jQuery.fn.addBack;

function sibling( cur, dir ) {
	do {
		cur = cur[ dir ];
	} while ( cur && cur.nodeType !== 1 );

	return cur;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( !runtil.test( name ) ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;

		if ( this.length > 1 && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}

		return this.pushStack( ret );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
			jQuery.find.matches(expr, elems);
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}

		return r;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {

	// Can't pass null or undefined to indexOf in Firefox 4
	// Set to 0 to skip string check
	qualifier = qualifier || 0;

	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			var retVal = !!qualifier.call( elem, i, elem );
			return retVal === keep;
		});

	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem ) {
			return ( elem === qualifier ) === keep;
		});

	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});

		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}

	return jQuery.grep(elements, function( elem ) {
		return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
	});
}
function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
		safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
	rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnoInnerhtml = /<(?:script|style|link)/i,
	manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /^$|\/(?:java|ecma)script/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,

	// We have to close these tags to support XHTML (#13200)
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		area: [ 1, "<map>", "</map>" ],
		param: [ 1, "<object>", "</object>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

		// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
		// unless wrapped in a div with non-breaking characters in front of it.
		_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>"  ]
	},
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement("div") );

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

jQuery.fn.extend({
	text: function( value ) {
		return jQuery.access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
		}, null, value, arguments.length );
	},

	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}

		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);

			if ( this[0].parentNode ) {
				wrap.insertBefore( this[0] );
			}

			wrap.map(function() {
				var elem = this;

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				return elem;
			}).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}

		return this.each(function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		});
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each(function(i) {
			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
		});
	},

	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},

	append: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				this.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				this.insertBefore( elem, this.firstChild );
			}
		});
	},

	before: function() {
		return this.domManip( arguments, false, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		});
	},

	after: function() {
		return this.domManip( arguments, false, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		});
	},

	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		var elem,
			i = 0;

		for ( ; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( getAll( elem ) );
				}

				if ( elem.parentNode ) {
					if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
						setGlobalEval( getAll( elem, "script" ) );
					}
					elem.parentNode.removeChild( elem );
				}
			}
		}

		return this;
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( getAll( elem, false ) );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}

			// If this is a select, ensure that it displays empty (#12336)
			// Support: IE<9
			if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
				elem.options.length = 0;
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function () {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},

	html: function( value ) {
		return jQuery.access( this, function( value ) {
			var elem = this[0] || {},
				i = 0,
				l = this.length;

			if ( value === undefined ) {
				return elem.nodeType === 1 ?
					elem.innerHTML.replace( rinlinejQuery, "" ) :
					undefined;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				( jQuery.support.htmlSerialize || !rnoshimcache.test( value )  ) &&
				( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
				!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {

				value = value.replace( rxhtmlTag, "<$1></$2>" );

				try {
					for (; i < l; i++ ) {
						// Remove element nodes and prevent memory leaks
						elem = this[i] || {};
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch(e) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function( value ) {
		var isFunc = jQuery.isFunction( value );

		// Make sure that the elements are removed from the DOM before they are inserted
		// this can help fix replacing a parent with child elements
		if ( !isFunc && typeof value !== "string" ) {
			value = jQuery( value ).not( this ).detach();
		}

		return this.domManip( [ value ], true, function( elem ) {
			var next = this.nextSibling,
				parent = this.parentNode;

			if ( parent ) {
				jQuery( this ).remove();
				parent.insertBefore( elem, next );
			}
		});
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, table, callback ) {

		// Flatten any nested arrays
		args = core_concat.apply( [], args );

		var first, node, hasScripts,
			scripts, doc, fragment,
			i = 0,
			l = this.length,
			set = this,
			iNoClone = l - 1,
			value = args[0],
			isFunction = jQuery.isFunction( value );

		// We can't cloneNode fragments that contain checked, in WebKit
		if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
			return this.each(function( index ) {
				var self = set.eq( index );
				if ( isFunction ) {
					args[0] = value.call( this, index, table ? self.html() : undefined );
				}
				self.domManip( args, table, callback );
			});
		}

		if ( l ) {
			fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
			first = fragment.firstChild;

			if ( fragment.childNodes.length === 1 ) {
				fragment = first;
			}

			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );
				scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
				hasScripts = scripts.length;

				// Use the original fragment for the last item instead of the first because it can end up
				// being emptied incorrectly in certain situations (#8070).
				for ( ; i < l; i++ ) {
					node = fragment;

					if ( i !== iNoClone ) {
						node = jQuery.clone( node, true, true );

						// Keep references to cloned scripts for later restoration
						if ( hasScripts ) {
							jQuery.merge( scripts, getAll( node, "script" ) );
						}
					}

					callback.call(
						table && jQuery.nodeName( this[i], "table" ) ?
							findOrAppend( this[i], "tbody" ) :
							this[i],
						node,
						i
					);
				}

				if ( hasScripts ) {
					doc = scripts[ scripts.length - 1 ].ownerDocument;

					// Reenable scripts
					jQuery.map( scripts, restoreScript );

					// Evaluate executable scripts on first document insertion
					for ( i = 0; i < hasScripts; i++ ) {
						node = scripts[ i ];
						if ( rscriptType.test( node.type || "" ) &&
							!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {

							if ( node.src ) {
								// Hope ajax is available...
								jQuery.ajax({
									url: node.src,
									type: "GET",
									dataType: "script",
									async: false,
									global: false,
									"throws": true
								});
							} else {
								jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
							}
						}
					}
				}

				// Fix #11809: Avoid leaking memory
				fragment = first = null;
			}
		}

		return this;
	}
});

function findOrAppend( elem, tag ) {
	return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	var attr = elem.getAttributeNode("type");
	elem.type = ( attr && attr.specified ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	var match = rscriptTypeMasked.exec( elem.type );
	if ( match ) {
		elem.type = match[1];
	} else {
		elem.removeAttribute("type");
	}
	return elem;
}

// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var elem,
		i = 0;
	for ( ; (elem = elems[i]) != null; i++ ) {
		jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
	}
}

function cloneCopyEvent( src, dest ) {

	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type, events[ type ][ i ] );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function fixCloneNodeIssues( src, dest ) {
	var nodeName, e, data;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	nodeName = dest.nodeName.toLowerCase();

	// IE6-8 copies events bound via attachEvent when using cloneNode.
	if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
		data = jQuery._data( dest );

		for ( e in data.events ) {
			jQuery.removeEvent( dest, e, data.handle );
		}

		// Event data gets referenced instead of copied if the expando gets copied too
		dest.removeAttribute( jQuery.expando );
	}

	// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
	if ( nodeName === "script" && dest.text !== src.text ) {
		disableScript( dest ).text = src.text;
		restoreScript( dest );

	// IE6-10 improperly clones children of object elements using classid.
	// IE10 throws NoModificationAllowedError if parent is null, #12132.
	} else if ( nodeName === "object" ) {
		if ( dest.parentNode ) {
			dest.outerHTML = src.outerHTML;
		}

		// This path appears unavoidable for IE9. When cloning an object
		// element in IE9, the outerHTML strategy above is not sufficient.
		// If the src has innerHTML and the destination does not,
		// copy the src.innerHTML into the dest.innerHTML. #10324
		if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
			dest.innerHTML = src.innerHTML;
		}

	} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set

		dest.defaultChecked = dest.checked = src.checked;

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.defaultSelected = dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			i = 0,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone(true);
			jQuery( insert[i] )[ original ]( elems );

			// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
			core_push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
});

function getAll( context, tag ) {
	var elems, elem,
		i = 0,
		found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
			typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
			undefined;

	if ( !found ) {
		for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
			if ( !tag || jQuery.nodeName( elem, tag ) ) {
				found.push( elem );
			} else {
				jQuery.merge( found, getAll( elem, tag ) );
			}
		}
	}

	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
		jQuery.merge( [ context ], found ) :
		found;
}

// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( manipulation_rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;
	}
}

jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var destElements, node, clone, i, srcElements,
			inPage = jQuery.contains( elem.ownerDocument, elem );

		if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
			clone = elem.cloneNode( true );

		// IE<=8 does not properly clone detached, unknown element nodes
		} else {
			fragmentDiv.innerHTML = elem.outerHTML;
			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
		}

		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {

			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			// Fix all IE cloning issues
			for ( i = 0; (node = srcElements[i]) != null; ++i ) {
				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[i] ) {
					fixCloneNodeIssues( node, destElements[i] );
				}
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0; (node = srcElements[i]) != null; i++ ) {
					cloneCopyEvent( node, destElements[i] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		destElements = srcElements = node = null;

		// Return the cloned set
		return clone;
	},

	buildFragment: function( elems, context, scripts, selection ) {
		var j, elem, contains,
			tmp, tag, tbody, wrap,
			l = elems.length,

			// Ensure a safe fragment
			safe = createSafeFragment( context ),

			nodes = [],
			i = 0;

		for ( ; i < l; i++ ) {
			elem = elems[ i ];

			if ( elem || elem === 0 ) {

				// Add nodes directly
				if ( jQuery.type( elem ) === "object" ) {
					jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

				// Convert non-html into a text node
				} else if ( !rhtml.test( elem ) ) {
					nodes.push( context.createTextNode( elem ) );

				// Convert html into DOM nodes
				} else {
					tmp = tmp || safe.appendChild( context.createElement("div") );

					// Deserialize a standard representation
					tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
					wrap = wrapMap[ tag ] || wrapMap._default;

					tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];

					// Descend through wrappers to the right content
					j = wrap[0];
					while ( j-- ) {
						tmp = tmp.lastChild;
					}

					// Manually add leading whitespace removed by IE
					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
						nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
					}

					// Remove IE's autoinserted <tbody> from table fragments
					if ( !jQuery.support.tbody ) {

						// String was a <table>, *may* have spurious <tbody>
						elem = tag === "table" && !rtbody.test( elem ) ?
							tmp.firstChild :

							// String was a bare <thead> or <tfoot>
							wrap[1] === "<table>" && !rtbody.test( elem ) ?
								tmp :
								0;

						j = elem && elem.childNodes.length;
						while ( j-- ) {
							if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
								elem.removeChild( tbody );
							}
						}
					}

					jQuery.merge( nodes, tmp.childNodes );

					// Fix #12392 for WebKit and IE > 9
					tmp.textContent = "";

					// Fix #12392 for oldIE
					while ( tmp.firstChild ) {
						tmp.removeChild( tmp.firstChild );
					}

					// Remember the top-level container for proper cleanup
					tmp = safe.lastChild;
				}
			}
		}

		// Fix #11356: Clear elements from fragment
		if ( tmp ) {
			safe.removeChild( tmp );
		}

		// Reset defaultChecked for any radios and checkboxes
		// about to be appended to the DOM in IE 6/7 (#8060)
		if ( !jQuery.support.appendChecked ) {
			jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
		}

		i = 0;
		while ( (elem = nodes[ i++ ]) ) {

			// #4087 - If origin and destination elements are the same, and this is
			// that element, do not do anything
			if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
				continue;
			}

			contains = jQuery.contains( elem.ownerDocument, elem );

			// Append to fragment
			tmp = getAll( safe.appendChild( elem ), "script" );

			// Preserve script evaluation history
			if ( contains ) {
				setGlobalEval( tmp );
			}

			// Capture executables
			if ( scripts ) {
				j = 0;
				while ( (elem = tmp[ j++ ]) ) {
					if ( rscriptType.test( elem.type || "" ) ) {
						scripts.push( elem );
					}
				}
			}
		}

		tmp = null;

		return safe;
	},

	cleanData: function( elems, /* internal */ acceptData ) {
		var elem, type, id, data,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			deleteExpando = jQuery.support.deleteExpando,
			special = jQuery.event.special;

		for ( ; (elem = elems[i]) != null; i++ ) {

			if ( acceptData || jQuery.acceptData( elem ) ) {

				id = elem[ internalKey ];
				data = id && cache[ id ];

				if ( data ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Remove cache only if it was not already removed by jQuery.event.remove
					if ( cache[ id ] ) {

						delete cache[ id ];

						// IE does not allow us to delete expando properties from nodes,
						// nor does it have a removeAttribute function on Document nodes;
						// we must handle all of these cases
						if ( deleteExpando ) {
							delete elem[ internalKey ];

						} else if ( typeof elem.removeAttribute !== core_strundefined ) {
							elem.removeAttribute( internalKey );

						} else {
							elem[ internalKey ] = null;
						}

						core_deletedIds.push( id );
					}
				}
			}
		}
	}
});
var iframe, getStyles, curCSS,
	ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity\s*=\s*([^)]*)/,
	rposition = /^(top|right|bottom|left)$/,
	// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
	// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rmargin = /^margin/,
	rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
	rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
	rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
	elemdisplay = { BODY: "block" },

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: 0,
		fontWeight: 400
	},

	cssExpand = [ "Top", "Right", "Bottom", "Left" ],
	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];

// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {

	// shortcut for names that are not vendor prefixed
	if ( name in style ) {
		return name;
	}

	// check for vendor prefixed names
	var capName = name.charAt(0).toUpperCase() + name.slice(1),
		origName = name,
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in style ) {
			return name;
		}
	}

	return origName;
}

function isHidden( elem, el ) {
	// isHidden might be called from jQuery#filter function;
	// in that case, element will be second argument
	elem = el || elem;
	return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}

function showHide( elements, show ) {
	var display, elem, hidden,
		values = [],
		index = 0,
		length = elements.length;

	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		values[ index ] = jQuery._data( elem, "olddisplay" );
		display = elem.style.display;
		if ( show ) {
			// Reset the inline display of this element to learn if it is
			// being hidden by cascaded rules or not
			if ( !values[ index ] && display === "none" ) {
				elem.style.display = "";
			}

			// Set elements which have been overridden with display: none
			// in a stylesheet to whatever the default browser style is
			// for such an element
			if ( elem.style.display === "" && isHidden( elem ) ) {
				values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
			}
		} else {

			if ( !values[ index ] ) {
				hidden = isHidden( elem );

				if ( display && display !== "none" || !hidden ) {
					jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
				}
			}
		}
	}

	// Set the display of most of the elements in a second loop
	// to avoid the constant reflow
	for ( index = 0; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}
		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
			elem.style.display = show ? values[ index ] || "" : "none";
		}
	}

	return elements;
}

jQuery.fn.extend({
	css: function( name, value ) {
		return jQuery.access( this, function( elem, name, value ) {
			var len, styles,
				map = {},
				i = 0;

			if ( jQuery.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	},
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		var bool = typeof state === "boolean";

		return this.each(function() {
			if ( bool ? state : isHidden( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		});
	}
});

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"columnCount": true,
		"fillOpacity": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = jQuery.camelCase( name ),
			style = elem.style;

		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// convert relative number strings (+= or -=) to relative numbers. #7345
			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
				// Fixes bug #9237
				type = "number";
			}

			// Make sure that NaN and null values aren't set. See: #7116
			if ( value == null || type === "number" && isNaN( value ) ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
			// but it would mean to define eight (for every problematic property) identical functions
			if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {

				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var num, val, hooks,
			origName = jQuery.camelCase( name );

		// Make sure that we're working with the right name
		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		//convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Return, converting to number if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
		}
		return val;
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback, args ) {
		var ret, name,
			old = {};

		// Remember the old values, and insert the new ones
		for ( name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		ret = callback.apply( elem, args || [] );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}

		return ret;
	}
});

// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
	getStyles = function( elem ) {
		return window.getComputedStyle( elem, null );
	};

	curCSS = function( elem, name, _computed ) {
		var width, minWidth, maxWidth,
			computed = _computed || getStyles( elem ),

			// getPropertyValue is only needed for .css('filter') in IE9, see #12537
			ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
			style = elem.style;

		if ( computed ) {

			if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
				ret = jQuery.style( elem, name );
			}

			// A tribute to the "awesome hack by Dean Edwards"
			// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
			// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
			// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
			if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {

				// Remember the original values
				width = style.width;
				minWidth = style.minWidth;
				maxWidth = style.maxWidth;

				// Put in the new values to get a computed value out
				style.minWidth = style.maxWidth = style.width = ret;
				ret = computed.width;

				// Revert the changed values
				style.width = width;
				style.minWidth = minWidth;
				style.maxWidth = maxWidth;
			}
		}

		return ret;
	};
} else if ( document.documentElement.currentStyle ) {
	getStyles = function( elem ) {
		return elem.currentStyle;
	};

	curCSS = function( elem, name, _computed ) {
		var left, rs, rsLeft,
			computed = _computed || getStyles( elem ),
			ret = computed ? computed[ name ] : undefined,
			style = elem.style;

		// Avoid setting ret to empty string here
		// so we don't default to auto
		if ( ret == null && style && style[ name ] ) {
			ret = style[ name ];
		}

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		// but not position css attributes, as those are proportional to the parent element instead
		// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
		if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

			// Remember the original values
			left = style.left;
			rs = elem.runtimeStyle;
			rsLeft = rs && rs.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				rs.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : ret;
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				rs.left = rsLeft;
			}
		}

		return ret === "" ? "auto" : ret;
	};
}

function setPositiveNumber( elem, value, subtract ) {
	var matches = rnumsplit.exec( value );
	return matches ?
		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
		value;
}

function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
	var i = extra === ( isBorderBox ? "border" : "content" ) ?
		// If we already have the right measurement, avoid augmentation
		4 :
		// Otherwise initialize for horizontal or vertical properties
		name === "width" ? 1 : 0,

		val = 0;

	for ( ; i < 4; i += 2 ) {
		// both box models exclude margin, so add it if we want it
		if ( extra === "margin" ) {
			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
		}

		if ( isBorderBox ) {
			// border-box includes padding, so remove it if we want content
			if ( extra === "content" ) {
				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// at this point, extra isn't border nor margin, so remove border
			if ( extra !== "margin" ) {
				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		} else {
			// at this point, extra isn't content, so add padding
			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// at this point, extra isn't content nor padding, so add border
			if ( extra !== "padding" ) {
				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	return val;
}

function getWidthOrHeight( elem, name, extra ) {

	// Start with offset property, which is equivalent to the border-box value
	var valueIsBorderBox = true,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
		styles = getStyles( elem ),
		isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

	// some non-html elements return undefined for offsetWidth, so check for null/undefined
	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
	if ( val <= 0 || val == null ) {
		// Fall back to computed then uncomputed css if necessary
		val = curCSS( elem, name, styles );
		if ( val < 0 || val == null ) {
			val = elem.style[ name ];
		}

		// Computed unit is not pixels. Stop here and return.
		if ( rnumnonpx.test(val) ) {
			return val;
		}

		// we need the check for style in case a browser which returns unreliable values
		// for getComputedStyle silently falls back to the reliable elem.style
		valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );

		// Normalize "", auto, and prepare for extra
		val = parseFloat( val ) || 0;
	}

	// use the active box-sizing model to add/subtract irrelevant styles
	return ( val +
		augmentWidthOrHeight(
			elem,
			name,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles
		)
	) + "px";
}

// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
	var doc = document,
		display = elemdisplay[ nodeName ];

	if ( !display ) {
		display = actualDisplay( nodeName, doc );

		// If the simple way fails, read from inside an iframe
		if ( display === "none" || !display ) {
			// Use the already-created iframe if possible
			iframe = ( iframe ||
				jQuery("<iframe frameborder='0' width='0' height='0'/>")
				.css( "cssText", "display:block !important" )
			).appendTo( doc.documentElement );

			// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
			doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
			doc.write("<!doctype html><html><body>");
			doc.close();

			display = actualDisplay( nodeName, doc );
			iframe.detach();
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return display;
}

// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
	var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
		display = jQuery.css( elem[0], "display" );
	elem.remove();
	return display;
}

jQuery.each([ "height", "width" ], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {
				// certain elements can have dimension info if we invisibly show them
				// however, it must have a current display style that would benefit from this
				return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
					jQuery.swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, name, extra );
					}) :
					getWidthOrHeight( elem, name, extra );
			}
		},

		set: function( elem, value, extra ) {
			var styles = extra && getStyles( elem );
			return setPositiveNumber( elem, value, extra ?
				augmentWidthOrHeight(
					elem,
					name,
					extra,
					jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				) : 0
			);
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
				( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle,
				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
			// if value === "", then remove inline opacity #12685
			if ( ( value >= 1 || value === "" ) &&
					jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
					style.removeAttribute ) {

				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
				// if "filter:" is present at all, clearType is disabled, we want to avoid this
				// style.removeAttribute is IE Only, but so apparently is this code path...
				style.removeAttribute( "filter" );

				// if there is no filter style applied in a css rule or unset inline opacity, we are done
				if ( value === "" || currentStyle && !currentStyle.filter ) {
					return;
				}
			}

			// otherwise, set new filter values
			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
	if ( !jQuery.support.reliableMarginRight ) {
		jQuery.cssHooks.marginRight = {
			get: function( elem, computed ) {
				if ( computed ) {
					// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
					// Work around by temporarily setting element display to inline-block
					return jQuery.swap( elem, { "display": "inline-block" },
						curCSS, [ elem, "marginRight" ] );
				}
			}
		};
	}

	// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
	// getComputedStyle returns percent when specified for top/left/bottom/right
	// rather than make the css module depend on the offset module, we just check for it here
	if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
		jQuery.each( [ "top", "left" ], function( i, prop ) {
			jQuery.cssHooks[ prop ] = {
				get: function( elem, computed ) {
					if ( computed ) {
						computed = curCSS( elem, prop );
						// if curCSS returns percentage, fallback to offset
						return rnumnonpx.test( computed ) ?
							jQuery( elem ).position()[ prop ] + "px" :
							computed;
					}
				}
			};
		});
	}

});

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		// Support: Opera <= 12.12
		// Opera reports offsetWidths and offsetHeights less than zero on some elements
		return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
			(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}

// These hooks are used by animate to expand properties
jQuery.each({
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// assumes a single number if not a string
				parts = typeof value === "string" ? value.split(" ") : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( !rmargin.test( prefix ) ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
});
var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

jQuery.fn.extend({
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map(function(){
			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		})
		.filter(function(){
			var type = this.type;
			// Use .is(":disabled") so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !manipulation_rcheckableType.test( type ) );
		})
		.map(function( i, elem ){
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val ){
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					}) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		}).get();
	}
});

//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, value ) {
			// If value is a function, invoke it and return its value
			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
		};

	// Set traditional to true for jQuery <= 1.3.2 behavior.
	if ( traditional === undefined ) {
		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		});

	} else {
		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" ).replace( r20, "+" );
};

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( jQuery.isArray( obj ) ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );

			} else {
				// Item is non-scalar (array or object), encode its numeric index.
				buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && jQuery.type( obj ) === "object" ) {
		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};
});

jQuery.fn.hover = function( fnOver, fnOut ) {
	return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
	// Document location
	ajaxLocParts,
	ajaxLocation,
	ajax_nonce = jQuery.now(),

	ajax_rquery = /\?/,
	rhash = /#.*$/,
	rts = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,

	// Keep a copy of the old load method
	_load = jQuery.fn.load,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat("*");

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.href;
}

// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];

		if ( jQuery.isFunction( func ) ) {
			// For each dataType in the dataTypeExpression
			while ( (dataType = dataTypes[i++]) ) {
				// Prepend if requested
				if ( dataType[0] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					(structure[ dataType ] = structure[ dataType ] || []).unshift( func );

				// Otherwise append
				} else {
					(structure[ dataType ] = structure[ dataType ] || []).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		});
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var deep, key,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

jQuery.fn.load = function( url, params, callback ) {
	if ( typeof url !== "string" && _load ) {
		return _load.apply( this, arguments );
	}

	var selector, response, type,
		self = this,
		off = url.indexOf(" ");

	if ( off >= 0 ) {
		selector = url.slice( off, url.length );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( jQuery.isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax({
			url: url,

			// if "type" variable is undefined, then "GET" method will be used
			type: type,
			dataType: "html",
			data: params
		}).done(function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		}).complete( callback && function( jqXHR, status ) {
			self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
		});
	}

	return this;
};

// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
	jQuery.fn[ type ] = function( fn ){
		return this.on( type, fn );
	};
});

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {
		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		return jQuery.ajax({
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		});
	};
});

jQuery.extend({

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: ajaxLocation,
		type: "GET",
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /xml/,
			html: /html/,
			json: /json/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": window.String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var // Cross-domain detection vars
			parts,
			// Loop variable
			i,
			// URL without anti-cache param
			cacheURL,
			// Response headers as string
			responseHeadersString,
			// timeout handle
			timeoutTimer,

			// To know if global events are to be dispatched
			fireGlobals,

			transport,
			// Response headers
			responseHeaders,
			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),
			// Callbacks context
			callbackContext = s.context || s,
			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
				jQuery( callbackContext ) :
				jQuery.event,
			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks("once memory"),
			// Status-dependent callbacks
			statusCode = s.statusCode || {},
			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},
			// The jqXHR state
			state = 0,
			// Default abort message
			strAbort = "canceled",
			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( (match = rheaders.exec( responseHeadersString )) ) {
								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match == null ? null : match;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					var lname = name.toLowerCase();
					if ( !state ) {
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( state < 2 ) {
							for ( code in map ) {
								// Lazy-add the new callback in a way that preserves old ones
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						} else {
							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR ).complete = completeDeferred.add;
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];

		// A cross-domain request is in order when we have a protocol:host:port mismatch
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
			);
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( state === 2 ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		fireGlobals = s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger("ajaxStart");
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		cacheURL = s.url;

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add anti-cache in url if needed
			if ( s.cache === false ) {
				s.url = rts.test( cacheURL ) ?

					// If there is already a '_' parameter, set its value
					cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :

					// Otherwise add one to the end
					cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
			}
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
			// Abort if not done already and return
			return jqXHR.abort();
		}

		// aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = setTimeout(function() {
					jqXHR.abort("timeout");
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch ( e ) {
				// Propagate exception as error if not done
				if ( state < 2 ) {
					done( -1, e );
				// Simply rethrow otherwise
				} else {
					throw e;
				}
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// If successful, handle type chaining
			if ( status >= 200 && status < 300 || status === 304 ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader("Last-Modified");
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader("etag");
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 ) {
					isSuccess = true;
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					isSuccess = true;
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					isSuccess = ajaxConvert( s, response );
					statusText = isSuccess.state;
					success = isSuccess.data;
					error = isSuccess.error;
					isSuccess = !error;
				}
			} else {
				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger("ajaxStop");
				}
			}
		}

		return jqXHR;
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	}
});

/* Handles responses to an ajax request:
 * - sets all responseXXX fields accordingly
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {
	var firstDataType, ct, finalDataType, type,
		contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields;

	// Fill responseXXX fields
	for ( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}

	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
	var conv2, current, conv, tmp,
		converters = {},
		i = 0,
		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice(),
		prev = dataTypes[ 0 ];

	// Apply the dataFilter if provided
	if ( s.dataFilter ) {
		response = s.dataFilter( response, s.dataType );
	}

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	// Convert to each sequential dataType, tolerating list modification
	for ( ; (current = dataTypes[++i]); ) {

		// There's only work to do if current dataType is non-auto
		if ( current !== "*" ) {

			// Convert response if prev dataType is non-auto and differs from current
			if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split(" ");
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {
								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.splice( i--, 0, current );
								}

								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s["throws"] ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
						}
					}
				}
			}

			// Update prev for next iteration
			prev = current;
		}
	}

	return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
	accepts: {
		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /(?:java|ecma)script/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
});

// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
});

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || jQuery("head")[0] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement("script");

				script.async = true;

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( script.parentNode ) {
							script.parentNode.removeChild( script );
						}

						// Dereference the script
						script = null;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};

				// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
				// Use native DOM manipulation to avoid our domManip AJAX trickery
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( undefined, true );
				}
			}
		};
	}
});
var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup({
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
});

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters["script json"] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always(function() {
			// Restore preexisting value
			window[ callbackName ] = overwritten;

			// Save back as free
			if ( s[ callbackName ] ) {
				// make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		});

		// Delegate to script
		return "script";
	}
});
var xhrCallbacks, xhrSupported,
	xhrId = 0,
	// #5280: Internet Explorer will keep connections alive if we don't abort on unload
	xhrOnUnloadAbort = window.ActiveXObject && function() {
		// Abort all pending requests
		var key;
		for ( key in xhrCallbacks ) {
			xhrCallbacks[ key ]( undefined, true );
		}
	};

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject("Microsoft.XMLHTTP");
	} catch( e ) {}
}

// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
	/* Microsoft failed to properly
	 * implement the XMLHttpRequest in IE7 (can't request local files),
	 * so we use the ActiveXObject when it is available
	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
	 * we need a fallback.
	 */
	function() {
		return !this.isLocal && createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;

// Create transport if the browser can provide an xhr
if ( xhrSupported ) {

	jQuery.ajaxTransport(function( s ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !s.crossDomain || jQuery.support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {

					// Get a new xhr
					var handle, i,
						xhr = s.xhr();

					// Open the socket
					// Passing null username, generates a login popup on Opera (#2865)
					if ( s.username ) {
						xhr.open( s.type, s.url, s.async, s.username, s.password );
					} else {
						xhr.open( s.type, s.url, s.async );
					}

					// Apply custom fields if provided
					if ( s.xhrFields ) {
						for ( i in s.xhrFields ) {
							xhr[ i ] = s.xhrFields[ i ];
						}
					}

					// Override mime type if needed
					if ( s.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( s.mimeType );
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
						headers["X-Requested-With"] = "XMLHttpRequest";
					}

					// Need an extra try/catch for cross domain requests in Firefox 3
					try {
						for ( i in headers ) {
							xhr.setRequestHeader( i, headers[ i ] );
						}
					} catch( err ) {}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( s.hasContent && s.data ) || null );

					// Listener
					callback = function( _, isAbort ) {
						var status, responseHeaders, statusText, responses;

						// Firefox throws exceptions when accessing properties
						// of an xhr when a network error occurred
						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
						try {

							// Was never called and is aborted or complete
							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {

								// Only called once
								callback = undefined;

								// Do not keep as active anymore
								if ( handle ) {
									xhr.onreadystatechange = jQuery.noop;
									if ( xhrOnUnloadAbort ) {
										delete xhrCallbacks[ handle ];
									}
								}

								// If it's an abort
								if ( isAbort ) {
									// Abort it manually if needed
									if ( xhr.readyState !== 4 ) {
										xhr.abort();
									}
								} else {
									responses = {};
									status = xhr.status;
									responseHeaders = xhr.getAllResponseHeaders();

									// When requesting binary data, IE6-9 will throw an exception
									// on any attempt to access responseText (#11426)
									if ( typeof xhr.responseText === "string" ) {
										responses.text = xhr.responseText;
									}

									// Firefox throws an exception when accessing
									// statusText for faulty cross-domain requests
									try {
										statusText = xhr.statusText;
									} catch( e ) {
										// We normalize with Webkit giving an empty statusText
										statusText = "";
									}

									// Filter status for non standard behaviors

									// If the request is local and we have data: assume a success
									// (success with no data won't get notified, that's the best we
									// can do given current implementations)
									if ( !status && s.isLocal && !s.crossDomain ) {
										status = responses.text ? 200 : 404;
									// IE - #1450: sometimes returns 1223 when it should be 204
									} else if ( status === 1223 ) {
										status = 204;
									}
								}
							}
						} catch( firefoxAccessException ) {
							if ( !isAbort ) {
								complete( -1, firefoxAccessException );
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, responseHeaders );
						}
					};

					if ( !s.async ) {
						// if we're in sync mode we fire the callback
						callback();
					} else if ( xhr.readyState === 4 ) {
						// (IE6 & IE7) if it's in cache and has been
						// retrieved directly we need to fire the callback
						setTimeout( callback );
					} else {
						handle = ++xhrId;
						if ( xhrOnUnloadAbort ) {
							// Create the active xhrs callbacks list if needed
							// and attach the unload handler
							if ( !xhrCallbacks ) {
								xhrCallbacks = {};
								jQuery( window ).unload( xhrOnUnloadAbort );
							}
							// Add to list of active xhrs callbacks
							xhrCallbacks[ handle ] = callback;
						}
						xhr.onreadystatechange = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback( undefined, true );
					}
				}
			};
		}
	});
}
var fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
	rrun = /queueHooks$/,
	animationPrefilters = [ defaultPrefilter ],
	tweeners = {
		"*": [function( prop, value ) {
			var end, unit,
				tween = this.createTween( prop, value ),
				parts = rfxnum.exec( value ),
				target = tween.cur(),
				start = +target || 0,
				scale = 1,
				maxIterations = 20;

			if ( parts ) {
				end = +parts[2];
				unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );

				// We need to compute starting value
				if ( unit !== "px" && start ) {
					// Iteratively approximate from a nonzero starting point
					// Prefer the current property, because this process will be trivial if it uses the same units
					// Fallback to end or a simple constant
					start = jQuery.css( tween.elem, prop, true ) || end || 1;

					do {
						// If previous iteration zeroed out, double until we get *something*
						// Use a string for doubling factor so we don't accidentally see scale as unchanged below
						scale = scale || ".5";

						// Adjust and apply
						start = start / scale;
						jQuery.style( tween.elem, prop, start + unit );

					// Update scale, tolerating zero or NaN from tween.cur()
					// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
					} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
				}

				tween.unit = unit;
				tween.start = start;
				// If a +=/-= token was provided, we're doing a relative animation
				tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
			}
			return tween;
		}]
	};

// Animations created synchronously will run synchronously
function createFxNow() {
	setTimeout(function() {
		fxNow = undefined;
	});
	return ( fxNow = jQuery.now() );
}

function createTweens( animation, props ) {
	jQuery.each( props, function( prop, value ) {
		var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
			index = 0,
			length = collection.length;
		for ( ; index < length; index++ ) {
			if ( collection[ index ].call( animation, prop, value ) ) {

				// we're done with this property
				return;
			}
		}
	});
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = animationPrefilters.length,
		deferred = jQuery.Deferred().always( function() {
			// don't match elem in the :animated selector
			delete tick.elem;
		}),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
				// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length ; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ]);

			if ( percent < 1 && length ) {
				return remaining;
			} else {
				deferred.resolveWith( elem, [ animation ] );
				return false;
			}
		},
		animation = deferred.promise({
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, { specialEasing: {} }, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,
					// if we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length ; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// resolve when we played the last frame
				// otherwise, reject
				if ( gotoEnd ) {
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		}),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length ; index++ ) {
		result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			return result;
		}
	}

	createTweens( animation, props );

	if ( jQuery.isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		})
	);

	// attach callbacks from options
	return animation.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );
}

function propFilter( props, specialEasing ) {
	var value, name, index, easing, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = jQuery.camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( jQuery.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// not quite $.extend, this wont overwrite keys already present.
			// also - reusing 'index' from above because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

jQuery.Animation = jQuery.extend( Animation, {

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.split(" ");
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			tweeners[ prop ] = tweeners[ prop ] || [];
			tweeners[ prop ].unshift( callback );
		}
	},

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			animationPrefilters.unshift( callback );
		} else {
			animationPrefilters.push( callback );
		}
	}
});

function defaultPrefilter( elem, props, opts ) {
	/*jshint validthis:true */
	var prop, index, length,
		value, dataShow, toggle,
		tween, hooks, oldfire,
		anim = this,
		style = elem.style,
		orig = {},
		handled = [],
		hidden = elem.nodeType && isHidden( elem );

	// handle queue: false promises
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always(function() {
			// doing this makes sure that the complete handler will be called
			// before this completes
			anim.always(function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			});
		});
	}

	// height/width overflow pass
	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
		// Make sure that nothing sneaks out
		// Record all 3 overflow attributes because IE does not
		// change the overflow attribute when overflowX and
		// overflowY are set to the same value
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Set display property to inline-block for height/width
		// animations on inline elements that are having width/height animated
		if ( jQuery.css( elem, "display" ) === "inline" &&
				jQuery.css( elem, "float" ) === "none" ) {

			// inline-level elements accept inline-block;
			// block-level elements need to be inline with layout
			if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
				style.display = "inline-block";

			} else {
				style.zoom = 1;
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		if ( !jQuery.support.shrinkWrapBlocks ) {
			anim.always(function() {
				style.overflow = opts.overflow[ 0 ];
				style.overflowX = opts.overflow[ 1 ];
				style.overflowY = opts.overflow[ 2 ];
			});
		}
	}


	// show/hide pass
	for ( index in props ) {
		value = props[ index ];
		if ( rfxtypes.exec( value ) ) {
			delete props[ index ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {
				continue;
			}
			handled.push( index );
		}
	}

	length = handled.length;
	if ( length ) {
		dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
		if ( "hidden" in dataShow ) {
			hidden = dataShow.hidden;
		}

		// store state if its toggle - enables .stop().toggle() to "reverse"
		if ( toggle ) {
			dataShow.hidden = !hidden;
		}
		if ( hidden ) {
			jQuery( elem ).show();
		} else {
			anim.done(function() {
				jQuery( elem ).hide();
			});
		}
		anim.done(function() {
			var prop;
			jQuery._removeData( elem, "fxshow" );
			for ( prop in orig ) {
				jQuery.style( elem, prop, orig[ prop ] );
			}
		});
		for ( index = 0 ; index < length ; index++ ) {
			prop = handled[ index ];
			tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
			orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );

			if ( !( prop in dataShow ) ) {
				dataShow[ prop ] = tween.start;
				if ( hidden ) {
					tween.end = tween.start;
					tween.start = prop === "width" || prop === "height" ? 1 : 0;
				}
			}
		}
	}
}

function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || "swing";
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			if ( tween.elem[ tween.prop ] != null &&
				(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
				return tween.elem[ tween.prop ];
			}

			// passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails
			// so, simple values such as "10px" are parsed to Float.
			// complex values such as "rotate(1rad)" are returned as is.
			result = jQuery.css( tween.elem, tween.prop, "" );
			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {
			// use step hook for back compat - use cssHook if its there - use .style if its
			// available and use plain properties where available
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes

Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
});

jQuery.fn.extend({
	fadeTo: function( speed, to, easing, callback ) {

		// show any hidden elements after setting opacity to 0
		return this.filter( isHidden ).css( "opacity", 0 ).show()

			// animate to the value specified
			.end().animate({ opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {
				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );
				doAnimation.finish = function() {
					anim.stop( true );
				};
				// Empty animations, or finishing resolves immediately
				if ( empty || jQuery._data( this, "finish" ) ) {
					anim.stop( true );
				}
			};
			doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each(function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = jQuery._data( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// start the next in the queue if the last step wasn't forced
			// timers currently will call their complete callbacks, which will dequeue
			// but only if they were gotoEnd
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		});
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each(function() {
			var index,
				data = jQuery._data( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// enable finishing flag on private data
			data.finish = true;

			// empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.cur && hooks.cur.finish ) {
				hooks.cur.finish.call( this );
			}

			// look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// turn off finishing flag
			delete data.finish;
		});
	}
});

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		attrs = { height: type },
		i = 0;

	// if we include width, step value is 1 to do all cssExpand values,
	// if we don't include width, step value is 2 to skip over Left and Right
	includeWidth = includeWidth? 1 : 0;
	for( ; i < 4 ; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show"),
	slideUp: genFx("hide"),
	slideToggle: genFx("toggle"),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
});

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			jQuery.isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
	};

	opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
		opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;

	// normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( jQuery.isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p*Math.PI ) / 2;
	}
};

jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
	var timer,
		timers = jQuery.timers,
		i = 0;

	fxNow = jQuery.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];
		// Checks the timer has not already been removed
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	if ( timer() && jQuery.timers.push( timer ) ) {
		jQuery.fx.start();
	}
};

jQuery.fx.interval = 13;

jQuery.fx.start = function() {
	if ( !timerId ) {
		timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.stop = function() {
	clearInterval( timerId );
	timerId = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,
	// Default speed
	_default: 400
};

// Back Compat <1.8 extension point
jQuery.fx.step = {};

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}
jQuery.fn.offset = function( options ) {
	if ( arguments.length ) {
		return options === undefined ?
			this :
			this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
	}

	var docElem, win,
		box = { top: 0, left: 0 },
		elem = this[ 0 ],
		doc = elem && elem.ownerDocument;

	if ( !doc ) {
		return;
	}

	docElem = doc.documentElement;

	// Make sure it's not a disconnected DOM node
	if ( !jQuery.contains( docElem, elem ) ) {
		return box;
	}

	// If we don't have gBCR, just use 0,0 rather than error
	// BlackBerry 5, iOS 3 (original iPhone)
	if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
		box = elem.getBoundingClientRect();
	}
	win = getWindow( doc );
	return {
		top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
		left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
	};
};

jQuery.offset = {

	setOffset: function( elem, options, i ) {
		var position = jQuery.css( elem, "position" );

		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		var curElem = jQuery( elem ),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css( elem, "top" ),
			curCSSLeft = jQuery.css( elem, "left" ),
			calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
			props = {}, curPosition = {}, curTop, curLeft;

		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;
		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};


jQuery.fn.extend({

	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset,
			parentOffset = { top: 0, left: 0 },
			elem = this[ 0 ];

		// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
		if ( jQuery.css( elem, "position" ) === "fixed" ) {
			// we assume that getBoundingClientRect is available when computed position is fixed
			offset = elem.getBoundingClientRect();
		} else {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();

			// Get correct offsets
			offset = this.offset();
			if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
				parentOffset = offsetParent.offset();
			}

			// Add offsetParent borders
			parentOffset.top  += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
			parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
		}

		// Subtract parent offsets and element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		return {
			top:  offset.top  - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
		};
	},

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.documentElement;
			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent || document.documentElement;
		});
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
	var top = /Y/.test( prop );

	jQuery.fn[ method ] = function( val ) {
		return jQuery.access( this, function( elem, method, val ) {
			var win = getWindow( elem );

			if ( val === undefined ) {
				return win ? (prop in win) ? win[ prop ] :
					win.document.documentElement[ method ] :
					elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : jQuery( win ).scrollLeft(),
					top ? val : jQuery( win ).scrollTop()
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length, null );
	};
});

function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
		// margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return jQuery.access( this, function( elem, type, value ) {
				var doc;

				if ( jQuery.isWindow( elem ) ) {
					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
					// isn't a whole lot we can do. See pull request at this URL for discussion:
					// https://github.com/jquery/jquery/pull/764
					return elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
					// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?
					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable, null );
		};
	});
});
// Limit scope pollution from any deprecated API
// (function() {

// })();
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
	define( "jquery", [], function () { return jQuery; } );
}

})( window );/**
 * jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery doTimeout: Like setTimeout, but better!
//
// *Version: 1.0, Last updated: 3/3/2010*
// 
// Project Home - http://benalman.com/projects/jquery-dotimeout-plugin/
// GitHub       - http://github.com/cowboy/jquery-dotimeout/
// Source       - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.js
// (Minified)   - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.min.js (1.0kb)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
// 
// Debouncing      - http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/
// Delays, Polling - http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/
// Hover Intent    - http://benalman.com/code/projects/jquery-dotimeout/examples/hoverintent/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.3.2, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome 4-5, Opera 9.6-10.1.
// Unit Tests      - http://benalman.com/code/projects/jquery-dotimeout/unit/
// 
// About: Release History
// 
// 1.0 - (3/3/2010) Callback can now be a string, in which case it will call
//       the appropriate $.method or $.fn.method, depending on where .doTimeout
//       was called. Callback must now return `true` (not just a truthy value)
//       to poll.
// 0.4 - (7/15/2009) Made the "id" argument optional, some other minor tweaks
// 0.3 - (6/25/2009) Initial release

(function($){
  '$:nomunge'; // Used by YUI compressor.
  
  var cache = {},
    
    // Reused internal string.
    doTimeout = 'doTimeout',
    
    // A convenient shortcut.
    aps = Array.prototype.slice;
  
  // Method: jQuery.doTimeout
  // 
  // Initialize, cancel, or force execution of a callback after a delay.
  // 
  // If delay and callback are specified, a doTimeout is initialized. The
  // callback will execute, asynchronously, after the delay. If an id is
  // specified, this doTimeout will override and cancel any existing doTimeout
  // with the same id. Any additional arguments will be passed into callback
  // when it is executed.
  // 
  // If the callback returns true, the doTimeout loop will execute again, after
  // the delay, creating a polling loop until the callback returns a non-true
  // value.
  // 
  // Note that if an id is not passed as the first argument, this doTimeout will
  // NOT be able to be manually canceled or forced. (for debouncing, be sure to
  // specify an id).
  // 
  // If id is specified, but delay and callback are not, the doTimeout will be
  // canceled without executing the callback. If force_mode is specified, the
  // callback will be executed, synchronously, but will only be allowed to
  // continue a polling loop if force_mode is true (provided the callback
  // returns true, of course). If force_mode is false, no polling loop will
  // continue, even if the callback returns true.
  // 
  // Usage:
  // 
  // > jQuery.doTimeout( [ id, ] delay, callback [, arg ... ] );
  // > jQuery.doTimeout( id [, force_mode ] );
  // 
  // Arguments:
  // 
  //  id - (String) An optional unique identifier for this doTimeout. If id is
  //    not specified, the doTimeout will NOT be able to be manually canceled or
  //    forced.
  //  delay - (Number) A zero-or-greater delay in milliseconds after which
  //    callback will be executed. 
  //  callback - (Function) A function to be executed after delay milliseconds.
  //  callback - (String) A jQuery method to be executed after delay
  //    milliseconds. This method will only poll if it explicitly returns
  //    true.
  //  force_mode - (Boolean) If true, execute that id's doTimeout callback
  //    immediately and synchronously, continuing any callback return-true
  //    polling loop. If false, execute the callback immediately and
  //    synchronously but do NOT continue a callback return-true polling loop.
  //    If omitted, cancel that id's doTimeout.
  // 
  // Returns:
  // 
  //  If force_mode is true, false or undefined and there is a
  //  yet-to-be-executed callback to cancel, true is returned, but if no
  //  callback remains to be executed, undefined is returned.
  
  $[doTimeout] = function() {
    return p_doTimeout.apply( window, [ 0 ].concat( aps.call( arguments ) ) );
  };
  
  // Method: jQuery.fn.doTimeout
  // 
  // Initialize, cancel, or force execution of a callback after a delay.
  // Operates like <jQuery.doTimeout>, but the passed callback executes in the
  // context of the jQuery collection of elements, and the id is stored as data
  // on the first element in that collection.
  // 
  // If delay and callback are specified, a doTimeout is initialized. The
  // callback will execute, asynchronously, after the delay. If an id is
  // specified, this doTimeout will override and cancel any existing doTimeout
  // with the same id. Any additional arguments will be passed into callback
  // when it is executed.
  // 
  // If the callback returns true, the doTimeout loop will execute again, after
  // the delay, creating a polling loop until the callback returns a non-true
  // value.
  // 
  // Note that if an id is not passed as the first argument, this doTimeout will
  // NOT be able to be manually canceled or forced (for debouncing, be sure to
  // specify an id).
  // 
  // If id is specified, but delay and callback are not, the doTimeout will be
  // canceled without executing the callback. If force_mode is specified, the
  // callback will be executed, synchronously, but will only be allowed to
  // continue a polling loop if force_mode is true (provided the callback
  // returns true, of course). If force_mode is false, no polling loop will
  // continue, even if the callback returns true.
  // 
  // Usage:
  // 
  // > jQuery('selector').doTimeout( [ id, ] delay, callback [, arg ... ] );
  // > jQuery('selector').doTimeout( id [, force_mode ] );
  // 
  // Arguments:
  // 
  //  id - (String) An optional unique identifier for this doTimeout, stored as
  //    jQuery data on the element. If id is not specified, the doTimeout will
  //    NOT be able to be manually canceled or forced.
  //  delay - (Number) A zero-or-greater delay in milliseconds after which
  //    callback will be executed. 
  //  callback - (Function) A function to be executed after delay milliseconds.
  //  callback - (String) A jQuery.fn method to be executed after delay
  //    milliseconds. This method will only poll if it explicitly returns
  //    true (most jQuery.fn methods return a jQuery object, and not `true`,
  //    which allows them to be chained and prevents polling).
  //  force_mode - (Boolean) If true, execute that id's doTimeout callback
  //    immediately and synchronously, continuing any callback return-true
  //    polling loop. If false, execute the callback immediately and
  //    synchronously but do NOT continue a callback return-true polling loop.
  //    If omitted, cancel that id's doTimeout.
  // 
  // Returns:
  // 
  //  When creating a <jQuery.fn.doTimeout>, the initial jQuery collection of
  //  elements is returned. Otherwise, if force_mode is true, false or undefined
  //  and there is a yet-to-be-executed callback to cancel, true is returned,
  //  but if no callback remains to be executed, undefined is returned.
  
  $.fn[doTimeout] = function() {
    var args = aps.call( arguments ),
      result = p_doTimeout.apply( this, [ doTimeout + args[0] ].concat( args ) );
    
    return typeof args[0] === 'number' || typeof args[1] === 'number'
      ? this
      : result;
  };
  
  function p_doTimeout( jquery_data_key ) {
    var that = this,
      elem,
      data = {},
      
      // Allows the plugin to call a string callback method.
      method_base = jquery_data_key ? $.fn : $,
      
      // Any additional arguments will be passed to the callback.
      args = arguments,
      slice_args = 4,
      
      id        = args[1],
      delay     = args[2],
      callback  = args[3];
    
    if ( typeof id !== 'string' ) {
      slice_args--;
      
      id        = jquery_data_key = 0;
      delay     = args[1];
      callback  = args[2];
    }
    
    // If id is passed, store a data reference either as .data on the first
    // element in a jQuery collection, or in the internal cache.
    if ( jquery_data_key ) { // Note: key is 'doTimeout' + id
      
      // Get id-object from the first element's data, otherwise initialize it to {}.
      elem = that.eq(0);
      elem.data( jquery_data_key, data = elem.data( jquery_data_key ) || {} );
      
    } else if ( id ) {
      // Get id-object from the cache, otherwise initialize it to {}.
      data = cache[ id ] || ( cache[ id ] = {} );
    }
    
    // Clear any existing timeout for this id.
    data.id && clearTimeout( data.id );
    delete data.id;
    
    // Clean up when necessary.
    function cleanup() {
      if ( jquery_data_key ) {
        elem.removeData( jquery_data_key );
      } else if ( id ) {
        delete cache[ id ];
      }
    };
    
    // Yes, there actually is a setTimeout call in here!
    function actually_setTimeout() {
      data.id = setTimeout( function(){ data.fn(); }, delay );
    };
    
    if ( callback ) {
      // A callback (and delay) were specified. Store the callback reference for
      // possible later use, and then setTimeout.
      data.fn = function( no_polling_loop ) {
        
        // If the callback value is a string, it is assumed to be the name of a
        // method on $ or $.fn depending on where doTimeout was executed.
        if ( typeof callback === 'string' ) {
          callback = method_base[ callback ];
        }
        
        callback.apply( that, aps.call( args, slice_args ) ) === true && !no_polling_loop
          
          // Since the callback returned true, and we're not specifically
          // canceling a polling loop, do it again!
          ? actually_setTimeout()
          
          // Otherwise, clean up and quit.
          : cleanup();
      };
      
      // Set that timeout!
      actually_setTimeout();
      
    } else if ( data.fn ) {
      // No callback passed. If force_mode (delay) is true, execute the data.fn
      // callback immediately, continuing any callback return-true polling loop.
      // If force_mode is false, execute the data.fn callback immediately but do
      // NOT continue a callback return-true polling loop. If force_mode is
      // undefined, simply clean up. Since data.fn was still defined, whatever
      // was supposed to happen hadn't yet, so return true.
      delay === undefined ? cleanup() : data.fn( delay === false );
      return true;
      
    } else {
      // Since no callback was passed, and data.fn isn't defined, it looks like
      // whatever was supposed to happen already did. Clean up and quit!
      cleanup();
    }
    
  };
  
})(jQuery);/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  File: Globals
  *  Dependencies: 
  * 	- None
  *  Functionality:
  *		- this adds some very basic general purpose globals for code bravity.
  *
  */
(function(window) {

	"use strict";

	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv GLOBAL FUNCTIONS  vvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
	
	window.isDefined = function(object) { return (typeof object !== 'undefined'); }; // specially to check for defined, may be falsy - but defined
	window.isNull = function(object) { return (object === null); }; // specially to check for null
	window.isEmpty = function(object) { return (object === ""); }; // specially to check for empty
	window.isFunction = function(object) { return (typeof object === 'function'); }; // if truthy and function
	window.isObject = function(object) { return (typeof object === 'object'); }; 
	window.isArray = function(object) { return (Object.prototype.toString.call(object) === '[object Array]'); }; // if truthy and an array
	window.isString = function(object) { return (typeof object === 'string' || object instanceof String); };
	window.isNumber = function(object) { return (typeof object === 'number' || object instanceof Number); };
	window.isBoolean = function(object) { return (typeof object === 'boolean' || object instanceof Boolean); };
	window.isDate = function(object) { return (object instanceof Date); };
	window.isLiteral = function(object) { return (object && !isString(object) && !isNumber(object) && !isBoolean(object) && !isDate(object) && !isArray(object) && !isFunction(object) && !object.prototype); };
	
}(window));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: framework kernel
  *  Dependencies: 
  * 	- jQuery 1.7.2 (or upwards)
  *			- http://jquery.com/
  *			- License: MIT/GPL
  * 	- jquery.ba.dotimeout.js v1.0 (or upwards)
  *			- http://benalman.com/projects/jquery-dotimeout-plugin/
  *			- License: MIT/GPL
  *  Functionality:
  *		- this is the kernel of the framework and glues everything together.
  *		- it does process other plugins.
  *
  */
(function(window) {

	"use strict";

	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvv FRAMEWORK DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
	
	// framework class (and root plugin)
	var _fluid = function() {
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvv PRIVATE VARS AND FUNCTIONS  vvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// self reference (internal)
		var $f = this;
							 
		// system info definition
		var systemInfo = { name: "fluid", title: "fluid", version: "0.0.0", author: "Vikas Burman", 
			copyright: "(c) 2012-2013 Vikas Burman, all rights reserved.", web: "http://fluidjs.vikasburman.com/", 
			license: { text: "Licensed under the terms of the MIT license.", url: "http://fluidjs.codeplex.com/license" }, 
			desc: "fluid - portable application framework" };
		
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvv BROWSER EVENT HANDLERS  vvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		
		// keeps track of time taken by last page refresh (only if isDebug = true)
		var performanceCounter = function(action) {
			switch(action.toLowerCase()) {
				case "set": {
					if ($f.config.options.isDebug && $f.sess) {
						$f.sess.set($f.config.refreshStartedAtSessionKey, (new Date().getTime()).toString());
					};
					break;
				};
				case "clear": {
					if ($f.config.options.isDebug && $f.sess) {
						var lastValue = Number($f.sess.get($f.config.refreshStartedAtSessionKey, "-1"));
						if (lastValue !== -1) {
							var msToRefresh = ((new Date().getTime() - lastValue)/1000);
							window.status = msToRefresh.toString() + " seconds";
						};
					};
					break;
				};
			};
		};

		// called when everything is finally done and app is ready for user
		var onReady = function() {
			// set message
			window.status = "Ready";

			// inform app finally
			var func = null;
			if ($f.app && isFunction($f.app.onReadyAll)) {
				func = $f.app.onReadyAll;
			} else {
				// else if there is a global function, inform that
				if (isFunction(window.onReadyAll)) {
					func = window.onReadyAll;
				};
			};
			if (isFunction(func)) {
				func();
			};

			// clear performance counter
			// clearing performace counter here means it does not
			// calculate panes loading time
			performanceCounter("clear");

			// set focus to page or view and window - as last thing
			if ($f.env && $f.env.has.feature("structuralElements")) {
				$("#" + $f.env.container.page()).focus();
			};
			window.focus();
			
			// all processing is done now
			// *READY*
		};
		
		// called when navigation is complete
		var onNavigationComplete = function() {
			// set message
			window.status = "Getting ready...";	
			
			// ready all plugins
			$.each($f.all.plugins("a"), function(i, plugin) {
				// forward to features
				plugin.forwardToFeatures("onReady");
				
				// call ready
				plugin.onReady();			
				
				// set flag
				plugin.handle.isReady = true;
				
				// add trace message
				$f.trace("Plugin '" + plugin.handle.name + "' is ready. Init: " + plugin.handle.isInit.toString() + ", Load: " + plugin.handle.isLoad.toString() + ", Ready: " + plugin.handle.isReady.toString() + ".");
			});	
		
			if ($f.state) {
				// reset flag to denote that all ready for all is called
				// now if a new plugin is loaded it's processing should be done elsewhere
				$f.state.isAllBatchReady = true;		
				
				// reset flag
				$f.state.isAppRestarting = false;
			};
			
			// set message
			window.status = "Showing...";			
			
			// hide loading animation
			var loadingContainer = ($f.env ? $f.env.container.loading() : "loadingBar"); // inbuilt default
			if (!isEmpty(loadingContainer)) {
				$("#" + loadingContainer).hide();
			};
			
			// show main container now - everyting should be visible now
			// if this is empty, means user did not want to show hide all the content
			var rootContainer = ($f.env ? $f.env.container.root() : "");
			if (!isEmpty(rootContainer)) {
				$("#" + rootContainer).css("display", "block");
			};

			// add trace message
			$f.trace("Navigation complete.");

			// now open all other panes, if there were any 
			// and go mark app as ready
			if ($f.has.feature("panes")) {
				$f.panes.resetAllASync("", function(data, isError) {
					// ready
					onReady();
				});
			} else {
				// ready
				onReady();
			};
		};
	
		// custom navigation
		// params:
		//	callBack (function): to call after custom navigation is done
		//	 					 It is passed on first navigation - but not passed
		//						 when hashTag is changed
		// returns (void):
		var performCustomNavigation = function(callBack) {
			// inform app 
			var func = null;
			if ($f.app && isFunction($f.app.onNavigationASync)) {
				func = $f.app.onNavigationASync;
			} else {
				// else if there is a global function, inform that
				if (isFunction(window.onNavigationASync)) {
					func = window.onNavigationASync;
				};
			};
			if (isFunction(func)) {
				// call function with callback
				func(callBack);
			} else {
				// call callback as final fallback
				// when no navigation is implemented
				if (isFunction(callBack)) {
					callBack();
				};
			};			
		};
		
		// navigate to ui
		var onNavigate = function() {
			// begin navigation
			window.status = "Opening...";	
		
			// since startup.html is already loaded when browser starts, static bindings cannot 
			// be resolved for any html content in base startup.html
			// so no <%?: %> tags are supported for startup html

			// process all post processors (since HTML is already loaded)
			if ($f.document) {
				$f.document.HTML.load("", "", {isSkipAllPreProcessors: true});
			};

			// add trace message
			$f.trace("Navigation begin.");
		
			// let navigator navigate us to desired place (this will end-up in onNavigationComplete)
			if ($f.nav) {
				$f.nav.navigateIn(onNavigationComplete);
			} else {
				// custom navigation with callback
				performCustomNavigation(onNavigationComplete);
			};	
		};
		
		// window load done
		var onLoad = function() {
			// controlled call forward - this is required to ensure that we release from here only when all is done
			var waitOnLogCounter = -1;
			$.doTimeout("allInitCheck", $f.vars.allPluginInitCheckInterval, function() {
				// check if any init is remaining
				var isRemaining = false;
				var failedBecause = "";
				waitOnLogCounter++;
				if (waitOnLogCounter >= 250) {
					waitOnLogCounter = 0;
				};
				$.each($f.vars.plugins, function(i, plugin) {
					if (!plugin.handle.isInit) {
						isRemaining = true;
						failedBecause = "Waiting to initialize: '" + plugin.handle.name + "'.";
						return false; // break
					};
				});
				
				if (!isRemaining) {
					// wait till complete framework assembly is not done
					isRemaining = !$f.vars.isAssemblyDone;
				};
				
				if (!isRemaining && !$f.info.version.package.isKernel()) { 
					// check for app plugin as well, since this is always loaded at the end
					// and it may have further plugins in its includeFiles list - so ensure that
					// this is also loaded - unless this is set to "off"
					if ($f.config.options.namedPlugins.app !== "off") {
						if (!$f.app || !$f.app.handle.isInit) {
							// reset
							isRemaining = true;
							failedBecause = "Waiting to initialize app plugin.";
						};
					};
				};
				
				// try and read file locally to ensure file system driver is working fine
				// this is required because java applet generally takes time to activate after
				// window.ready is called
				if (!isRemaining && $f.config.options.isEnableLocalFileSystemAccess) {
					var localDataPlaceholderFile = $f.IO.folder.getCompletePath("%DATA%/data.txt");
					$f.vars.isSupressShowingErrorOnce = true; // this will skip showing error once and then will reset
					if ($f.IO.file.read(localDataPlaceholderFile, "") === null) {
						// reset
						isRemaining = true;
						failedBecause = "Waiting to initialize file system access.";
					} else {
						$f.trace("File system access initialized.");
					};
				};
				
				if (!isRemaining) { 
					// good to continue now
					// set message
					window.status = "Configuring...";	
					
					// configure framework and all plugins from all those plugins which can configure plugins
					// and vice versa
					// order is not important
					$.each($f.all.plugins("a"), function(i, plugin) {
						configurePlugin(plugin, false, false); // since this is batch processing itself, pass false from here
					});

					// set message
					window.status = "Loading...";	
					
					// load all plugins
					$.each($f.all.plugins("a"), function(i, plugin) {
						// forward to features
						plugin.forwardToFeatures("onLoad");
						
						// call load
						plugin.onLoad();
						
						// set flag
						plugin.handle.isLoad = true;
						
						// add trace message
						$f.trace("Plugin '" + plugin.handle.name + "' is loaded. Init: " + plugin.handle.isInit.toString() + ", Load: " + plugin.handle.isLoad.toString() + ", Ready: " + plugin.handle.isReady.toString() + ".");
					});
					
					// reset flag to denote that all basics (states, resources, etc.) are processed in batch
					// now if a new plugin is loaded it's processing should be done elsewhere
					// (should be called just before navigator is called)
					if ($f.state) {
						$f.state.isAllBatchLoaded = true;
					};
					
					// navigate
					onNavigate();
					
					// done
					return false; // so it does not poll
				} else {
					// add to trace - only periodically
					if (waitOnLogCounter === 0) {
						$f.trace(failedBecause);
					};
					
					// show in window message as well
					window.status = failedBecause;
					
					// return
					return true; // so it polls again											
				};
			});	
		};
	
		// window unload hapenning for whatever reason
		// alerts might not work from within this functiuon
		var onUnload = function() {
			// set message
			window.status = "Unloading...";	
			
			// reset flag (called before saving states, so these are saved)
			if ($f.state) {
				$f.state.isAllBatchLoaded = false;
				$f.state.isAllBatchReady = false;
			};
			
			// unload all plugins
			$.each($f.all.plugins("d"), function(i, plugin) {
				// forward to features
				plugin.forwardToFeatures("onUnload");
							
				// call unload
				plugin.onUnload();			
				
				// add trace message
				$f.trace("Plugin '" + plugin.handle.name + "' is unloaded.");
			});	
		
			// set message
			window.status = "Unloaded.";		
			
			// set performance counter
			performanceCounter("set");
		};	
		
		// browser offline/online state change
		var onOnLineOffLine = function() {
			// get state
			var state = (navigator.onLine ? "online" : "offline");
			
			// show status
			window.status = state;
			
			// inform app
			if ($f.app && isFunction($f.app.onBrowserStateChange)) {
				$f.app.onBrowserStateChange(state);
			};	
		};
		
		// catch unhandled error and route it to application error handler (intentionally not used jquery bindings here)
		var isHandlingError = false;
		var onError = function(message, url, lineNumber) {
			var success = true;
			if (!isHandlingError) {
				// set flag
				isHandlingError = true;
				
				// inform app 
				var func = null;
				if ($f.app && isFunction($f.app.onApplicationError)) {
					func = $f.app.onApplicationError;
				} else {
					// else if there is a global function, inform that
					if (isFunction(window.onApplicationError)) {
						func = window.onApplicationError;
					};
				};
				if (isFunction(func)) {
					// call function 
					success = func(message, url, lineNumber);
				} else {
					// just show the error, cannot handle
					$f.error(message, true, false);
					
					// reset success state, so if a dialog is to be shown it should
					success = false;
				};
			
				// reset
				isHandlingError = false;
			} else {
				$f.error("Fatal error. Please restart the application.", true, false);
			};
			
			// return (true means browser error dialog would show up, else not)
			return success;	
		};
		
		// hash change handler
		var onHashChange = function() {
			var isGo = true;
			if ($f.state) {
				isGo = $f.state.isAllBatchReady;
			};
			
			// let navigator handle navigation or go for custom navigation
			if (isGo) {
				if ($f.nav) {
					$f.nav.navigateOnHashChange(); 
				} else {
					performCustomNavigation(); // called without callback
				};
			};
		};
		
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN FUNCTIONALITY  vvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

		// framework plugins - reserved names (special inbuilt names, dev tool names)
		var fixedPluginNames = "'master_default', 'page_default', 'app', 'page', 'master', 'view', ";
			fixedPluginNames += "'emulator', 'devCorner', 'testBench', ";
		
		// break version info into known parts
		// params:
		//	version (string): version string in MAJOR.MINOR.BUILD format
		// returns (object): version object
		var breakVersionInfo = function(version) {
			var newVer = {
				version: "",
				major: "",
				minor: "",
				build: ""
			};
			
			// break
			try {
				newVer.version = version;
				var parts = version.split(".");
				newVer.major = parts[0];
				newVer.minor = parts[1];
				newVer.build = parts[2];
			} catch (ex) {
				// ignore
			};

			// return
			return newVer;
		};

		// configure given plugin from those plugins which can configure other plugins and 
		// configure other plugins by given plugin if it can configure other plugins
		// params:
		//	plugin (object): plugin object to configure
		//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
		//                                        this plugin otherwise should also be done now with
		//                                        this plugin, because this is being loaded after all
		//                                        batch processing is done at load time
		//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
		// 										    a new feature is added to plugin which may have added
		//											some members those required reconfiguration
		// returns (void):
		var configurePlugin = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {
			// create a list of plugins which can configure other plugins
			// check all other plugins which are available as of now, including this plugin itself
			// order is not important
			var pluginsList = [];
			$.each($f.all.plugins("a"), function(i, plg) {
				if (plg.config.canConfigurePlugins) {
					pluginsList.push(plg);
				};
			});			
			
			// configure this plugin by all those plugins which can configure other plugins (including self)
			$.each(pluginsList, function(i, plg) {
				if (!isReconfigureOnNewFeatureAdd) {
					// process only if this has not already configured this plugin
					if (plugin.handle.configuredBy.indexOf("'" + plg.handle.id + "'") === -1) {
						plg.configure(plugin, isPerformOnLoadProcessAlso); 
						plugin.handle.configuredBy += ", '" + plg.handle.id + "'";
						$f.trace("'" + plg.handle.name + "' configured '" + plugin.handle.name + "'.");
					};
				} else {
					// process even if this was already configured
					plg.configure(plugin, isPerformOnLoadProcessAlso); 
				};
			});			

			// let this plugin configure other plugins, but only if this is not
			// reconfigure case
			if (!isReconfigureOnNewFeatureAdd) {
				// if this plugin can configure other plugins, let it process other plugins
				// excluding self because it must have processed itself in above loop already
				// for one case when "plg" and "plugin" are same at line "plg.configure(plugin);" above
				if (plugin.config.canConfigurePlugins) {
					// process framework and all available plugins if it has not already configured by this plugin
					$.each($f.all.plugins("a"), function(i, plg) {
						// process framework only if this has not already configured this plugin
						if (plg.handle.configuredBy.indexOf("'" + plugin.handle.id + "'") === -1) {			
							plugin.configure(plg, isPerformOnLoadProcessAlso);
							plg.handle.configuredBy += ", '" + plugin.handle.id + "'";
							$f.trace("'" + plugin.handle.name + "' configured '" + plg.handle.name + "'.");
						};
					});				
				};
			};
			
			// add trace message
			if (!isReconfigureOnNewFeatureAdd) {			
				$f.trace("Plugin '" + plugin.handle.name + "' is configured. Init: " + plugin.handle.isInit.toString() + ", Load: " + plugin.handle.isLoad.toString() + ", Ready: " + plugin.handle.isReady.toString() + ".");
			} else {
				$f.trace("Plugin '" + plugin.handle.name + "' is re-configured because a new feature was added to it.");
			};
		};

		// plugin extender
		// params:
		//  plugin (object): plugin object that is to be extended
		// 	extender (object literal): object that is to be merged with given plugin object to extend it
		// returns (object): extended plugin
		var pluginExtender = function(plugin, extender) {
			// merge-extend members from given extender into given plugin using given extension options
			$.each(extender, function(name, value) {
				// copy only if not in ignore list at level 0
				if (plugin.handle.extensionOptions.ignore.indexOf("'" + name + "'") === -1) {
					// perform partial copy if name is in partial copy list at level 0
					if (plugin.handle.extensionOptions.partialCopy.hasOwnProperty(name)) {
						// perform partial copy (if defined) or else copy as is
						if (!isDefined(plugin[name])) {
							// since not defined at this level perform complete copy
							plugin[name] = value;
						} else {
							$.each(value, function(name2, value2) {
								// copy only if not in ignore list at level 1
								if (plugin.handle.extensionOptions.partialCopy[name].indexOf("'" + name2 + "'") === -1) {
									plugin[name][name2] = value2;
								} else {
									// ignore copying this
								};
							});
						};
					} else {
						// perform complete copy
						plugin[name] = value;
					};
				} else {
					// ignore copying this
				};
			});

			// create aggregated extensionOptions
			var extensionOptions = plugin.handle.extensionOptions;
			var extenderOptions = null;
			if (extender.handle && extender.handle.extensionOptions) {
				extenderOptions = extender.handle.extensionOptions;
			};
			
			// merge-update extensionOptions using definitions defined in extenderOptions
			if (!isNull(extenderOptions)) {
				// process each extenderOption in extenderOptions
				$.each(extenderOptions, function(itemName, extenderOption) {
					if (itemName === 'ignore') {
						// merge-update ignore list at level 0
						extensionOptions.ignore = extensionOptions.ignore + extenderOption;
					} else if (itemName === 'partialCopy') {
						// merge-update ignore list at level 1
						$.each(extenderOption, function(name, value) {
							if (!isDefined(extensionOptions.partialCopy[name])) {
								extensionOptions.partialCopy[name] = value;
							} else {
								extensionOptions.partialCopy[name] = extensionOptions.partialCopy[name] + value;
							};
						});				
					};
				});
			};

			// update extension options (for next extension)
			plugin.handle.extensionOptions = extensionOptions;

			// return
			return plugin;
		};

		// adds a plugin
		// params:
		//	type (string): type of the plugin to add
		//  namespace (string): namespace of the plugin to add to framework
		//	name (string): name of the plugin to add to framework
		// 	isFixedName (boolean): if this plugin name is a one of the fixed names
		//	alias (string): a unique 2 to 4 characters alias for the plugin
		//                  this might be required only for most used plugins
		//					can be used only with non-namespaced and non-module type plugins
		//	id (string): guid of the plugin
		// 	extender (class definition): instance of that is merge-updated with plugin object to extend it
		// returns (object): returns plugin object if added, null otherwise
		var addPlugin = function(type, namespace, name, isFixedName, alias, id, extender) {
			// extend, if this is not supressed
			var success = !$f.config.options.isSupressPluginExtension;
			if (!success) {
				$f.trace("Cannot load plugin '" + name + "' because extension is currently supressed.");
				return null;
			};		
			
			// handle simulation case
			// Note: only kernel and core can be simulated
			if (!isEmpty($f.config.options.simulatePackage) && fluidOptions) {
				if ($f.info.version.package.isKernel() && isDefined(fluidOptions.bundledKernelPluginNames)) { 
					if (fluidOptions.bundledKernelPluginNames.indexOf("'" + name + "'") === -1) {
						$f.trace("Plugin '" + name + "' is not part of kernel package. Skipped loading for simulation.");
						return null;
					};
				} else if ($f.info.version.package.isCore() && isDefined(fluidOptions.bundledCorePluginNames)) {
					if (fluidOptions.bundledCorePluginNames.indexOf("'" + name + "'") === -1) {
						$f.trace("Plugin '" + name + "' is not part of core package. Skipped loading for simulation.");
						return null;
					};
				};
			};
			
			// check if this is module plugin
			var isModulePlugin = false;
			if (type === $f.p.plugins.types.module) {
				isModulePlugin = true;
			};
			
			// check if this is pane plugin
			var isPanePlugin = false;
			if (type === $f.p.plugins.types.pane) {
				isPanePlugin = true;
			};
			
			// error, if already loaded
			var completeName = "";
			var listedName = "";
			if (isEmpty(namespace)) {
				completeName = name;
				if (isModulePlugin) {
					listedName = "_modules_" + name;
				} else if (isPanePlugin) {
					listedName = "_panes_" + name;
				} else {
					listedName = "_" + name;
				};
			} else {
				completeName = namespace + "." + name;
				if (isModulePlugin) {
					listedName = "_modules_ns_" + completeName.replace(/./g, "_"); 
				} else if (isPanePlugin) {
					listedName = "_panes_ns_" + completeName.replace(/./g, "_"); 
				} else {
					listedName = "_ns_" + completeName.replace(/./g, "_"); 
				};
			};
			if (isDefined($f.vars.pluginsNamedList[listedName])) {
				if (isModulePlugin) {
					$f.trace("Module '" + completeName + "' is already loaded.");
				} else if (isPanePlugin) {
					$f.trace("Pane '" + completeName + "' is already loaded.");
				} else {
					$f.trace("Plugin '" + completeName + "' is already loaded.");
				};
				return null;
			};	
			
			// error if it is a fixed name but not coming from a fixed name call-path
			if (isFixedName) {
				if (fixedPluginNames.indexOf("'" + name + "'") === -1) {
					$f.trace("Plugin '" + completeName + "' (fixed) is not known.");
					return null;
				};
			} else {
				if (fixedPluginNames.indexOf("'" + name + "'") !== -1) {
					$f.trace("Cannot use a fixed plugin '" + completeName + "'.");
					return null;			
				};			
			};
			
			// reserved names (names which are used by framework or will be used by framework) cannot be used for plugins and modules
			if (isEmpty(namespace)) {
				var reservedNames = "";
				if (!isModulePlugin && !isPanePlugin) {
					// all the object/property names of $f object - TODO: Update this list
					reservedNames = "'handle', 'info', 'host', 'window', 'config', 'state', 'session', 'cache', 'include', 'resources', 'modules', 'panes', 'p', 'ns', 'vars', 'settings', 'events', 'aspects', 'weavings', 'hotkeys', 'jobs', 'workflows', 'services', 'db', 'functions', 'all', 'get', 'exec', 'extend', 'onpreinit', 'oninit', 'onready', 'onload', 'onunload', 'trace', 'has', 'reset', 'restart', 'error', 'alert', 'confirm', 'prompt', ";
					if (reservedNames && reservedNames.indexOf("'" + name.toLowerCase() + "'") !== -1) {
						$f.trace("'" + name + "' is a reserved name. Cannot extend.");
						return null;
					};
				};
			};
			
			// check for alias validity
			var useAlias = false;
			if (!isEmpty(alias)) {
				if (!isEmpty(namespace) || isModulePlugin || isPanePlugin) {
					$f.trace("Alias can be used only for non-module or non-pane plugins which belongs to global namespace. Cannot extend '" + name + "'.");
					return null;
				} else if (alias === name) {
					$f.trace("Alias can not be same as name. Cannot extend '" + name + "'.");
					return null;
				} else if ($f[alias]){
					$f.trace("Alias '" + alias + "' is alread in use. Cannot extend '" + name + "'.");
					return null;
				} else {
					useAlias = true;
				};
			};
			
			// create new plugin object
			var pluginBaseClass = $f.p.plugins.classes.pluginBase;
			var plugin = new pluginBaseClass();
			
			// extend it as required
			var extendedBaseClass = $f.p.plugins.classes[type + "PluginBase"]; // classname convention is to suffix PluginBase to name of the plugin type
			if (!extendedBaseClass) {
				$f.trace("'" + completeName + "' plugin's type '" + type + "' is not registered. Not loaded.");
				return null;
			};
			plugin = pluginExtender(plugin, new extendedBaseClass(plugin));
			if (isNull(plugin)) {
				$f.trace("'" + completeName + "' plugin's type '" + type + "' is unknown. Not loaded.");
				return null;
			};
			
			// reset certain properties of new plugin
			plugin.handle.id = id;
			plugin.handle.namespace = namespace;
			plugin.handle.name = name;
			plugin.handle.type = type;
			plugin.host = $f;
			
			// qualified name
			var qualifiedName = "$f.";
			if (!isEmpty(namespace)) {
				if (isModulePlugin) {
					qualifiedName = qualifiedName + "modules.ns." + namespace + "." + name;
				} else if (isPanePlugin) {
					qualifiedName = qualifiedName + "panes.ns." + namespace + "." + name;
				} else {
					qualifiedName = qualifiedName + "ns." + namespace + "." + name;
				};
			} else {
				if (isModulePlugin) {
					qualifiedName = qualifiedName + "modules." + name;
				} else if (isPanePlugin) {
					qualifiedName = qualifiedName + "panes." + name;
				} else {
					qualifiedName = qualifiedName + name;
				};
			};
			plugin.handle.qualifiedName = qualifiedName;		
			
			// extend the plugin using given extender
			var extenderInstance = new extender(plugin);
			plugin = pluginExtender(plugin, extenderInstance);
			$f.trace("Plugin '" + completeName + "' instantiated.");
			
			// inform app about this plugin
			if ($f.app && isFunction($f.app.onBeforePluginLoad)) {
				if (!$f.app.onBeforePluginLoad(plugin)) {
					$f.trace("Application decided not to load plugin '" + completeName + "'. Load skipped.");
					return null;
				};
			};
			
			// execute onPreInit
			if (isFunction(extenderInstance.onPreInit)) {
				if (!extenderInstance.onPreInit()) {
					$f.trace("Plugin '" + completeName + "' decided not to be loaded. Load skipped.");
					return null;
				};
			};
			
			// load
			if (isEmpty(namespace)) {
				if (isModulePlugin) {		
					if (!$f.modules) { $f.modules = {}; };
					$f.modules[name] = plugin;
				} else if (isPanePlugin) {
					if (!$f.panes) { $f.panes = {}; };
					$f.panes[name] = plugin;
				} else {
					$f[name] = plugin;
				};
			} else {
				// get root object
				var rootObject = null;
				if (isModulePlugin) {
					if (!$f.modules) { $f.modules = {}; };
					if (!$f.modules.ns) { $f.modules.ns = {}; };
					rootObject = $f.modules.ns;
				} else if (isPanePlugin) {
					if (!$f.panes) { $f.panes = {}; };
					if (!$f.panes.ns) { $f.panes.ns = {}; };
					rootObject = $f.panes.ns;
				} else {
					rootObject = $f.ns;
				};
				
				// build-up namespace
				var namespaceItems = [];
				if (namespace.indexOf(".") !== -1) {
					namespaceItems = namespace.split(".");
				} else {
					namespaceItems.push(namespace);
				};
				var lastObject = rootObject;
				$.each(namespaceItems, function(i, ns) {
					// add an empty object if not defined
					if (!isDefined(lastObject[ns])) {
						lastObject[ns] = {};
					};
					
					// pick this object as next level
					lastObject = lastObject[ns];
				});
				
				// add plugin
				lastObject[name] = plugin;
			};
			$f.vars.plugins.push(plugin);
			$f.vars.pluginsNamedList[listedName] = plugin;
			$f.vars.pluginsSortedList.ascending = null; // so it updates the cache whenever required next
			$f.vars.pluginsSortedList.descending = null; // so it updates the cache whenever required next

			// alias
			if (useAlias) {
				plugin.handle.alias = alias;
				$f[alias] = plugin;
			} else {
				plugin.handle.alias = "";
			};		
			
			// pick framework's version, author, copyright and web link
			// for all system plugins (if not defined)
			if (plugin.handle.isSystemPlugin) {
				if (isEmpty(plugin.info.version)) {
					plugin.info.version = systemInfo.version;
				};
				if (isEmpty(plugin.info.author)) {
					plugin.info.author = systemInfo.author;
				};
				if (isEmpty(plugin.info.copyright)) {
					plugin.info.copyright = systemInfo.copyright;
				};
				if (isEmpty(plugin.info.web)) {
					plugin.info.web = systemInfo.web;
				};
				if (isEmpty(plugin.info.license.text)) {
					plugin.info.license.text = systemInfo.license.text;
				};						
				if (isEmpty(plugin.info.license.url)) {
					plugin.info.license.url = systemInfo.license.url;
				};				
			};			
			
			// pick app's version, author, copyright and web link
			// for module, page, app's pane and master - if not already specified
			if (plugin.handle.isAppPlugin && $f.app) {
				if (isEmpty(plugin.info.version)) {
					plugin.info.version = $f.app.info.version;
				};
				if (isEmpty(plugin.info.author)) {
					plugin.info.author = $f.app.info.author;
				};
				if (isEmpty(plugin.info.copyright)) {
					plugin.info.copyright = $f.app.info.copyright;
				};
				if (isEmpty(plugin.info.web)) {
					plugin.info.web = $f.app.info.web;
				};
				if (isEmpty(plugin.info.license.text)) {
					plugin.info.license.text = $f.app.info.license.text;
				};						
				if (isEmpty(plugin.info.license.url)) {
					plugin.info.license.url = $f.app.info.license.url;
				};				
			};
			
			// break version into known parts
			plugin.info.version = breakVersionInfo(plugin.info.version);
			
			// add all features that apply to this plugin
			addAllFeaturesToThisTarget(plugin);	
			
			// all extensions done
			plugin.handle.onExtensionComplete();
			
			// special case to initialize environment plugin - right here
			// before including files, for all other cases onInit is called after
			// files are included
			if (plugin.handle.name === "environment") {
				if (!plugin.onInit()) {
					// source of several troubles, throw an error for this
					$f.error("'" + name + "' plugin failed to initialize.", true, true);
				} else 	{
					// set as initialized (this will prevent calling onInit() second time in onIncludeComplete())
					plugin.handle.isInit = true;
					
					// add trace message
					$f.trace("Plugin '" + plugin.handle.name + "' is initialized. Init: " + plugin.handle.isInit.toString() + ", Load: " + plugin.handle.isLoad.toString() + ", Ready: " + plugin.handle.isReady.toString() + ".");
				};
			};

			// initiate include processing if include is defined on plugin
			// or this is an app plugin (which might have plugins definition
			// and this condition will also cause devPlugins and fluidPlugins to process
			if ((plugin.include && isArray(plugin.include)) || plugin.handle.isApp()) {
				// special case for kernel-only case
				// since there are NO system plugins in this case, 
				// therefore send all plugins to completion directly
				// as in this case includes will not be processed
				if ($f.info.version.package.isKernel()) {
					// directly send it for completion, since includes cannot be processed
					plugin.handle.onIncludeComplete();
				} else if ($f.vars.isAssemblyDone) {
					if (!$f.IO) { 
						// if assembly is done and somehow IO is not available
						// and this is an external plugin which is being loaded by 
						// inclusion in startup file or somehow
						// directly send it for completion, since includes cannot be processed
						plugin.handle.onIncludeComplete();					
					} else {		
						// include all files of the plugin - after $f.IO is completely available (ASync)
						if ($f.document && $f.document.has.feature("fileInclude")) {
							$f.document.includeFiles(plugin); // (this will end-up in plugin.handle.onIncludeComplete())
						} else {
							// directly send it for completion, since includes cannot be processed
							plugin.handle.onIncludeComplete();
						};
					};
				} else {
					if (!$f.IO) { 
						// add to queue, when IO will be loaded, it will call include for
						// all queued plugins
						$f.vars.pendingIncludeFilesQueue.push(plugin);					
					} else {		
						// include all files of the plugin - after $f.IO is completely available (ASync)
						if ($f.document && $f.document.has.feature("fileInclude")) {
							$f.document.includeFiles(plugin); // (this will end-up in plugin.handle.onIncludeComplete())
						} else {
							// directly send it for completion, since includes cannot be processed
							plugin.handle.onIncludeComplete();
						};
					};
				};	
			} else {
				// directly send it for completion, since no includes are available
				plugin.handle.onIncludeComplete();
			};

			// return
			return plugin;
		};

		// finds the already loaded plugin and returns its instance
		// params:
		//	name (string): name of the plugin to look for
		//	               if plugin has namespace in it, it should be part of this string
		//  type (string): type of plugin
		//				   "pane", "module", "plugin", "" (empty means "plugin")
		// return (object): returns plugin object if success, null otherwise	
		var getPlugin = function(name, type) {
			// if autosearch is to be done
			// autosearch, looks for plugin first, then for module and then for pane
			var isAutoSearch = false;
			if (arguments.length === 1) {
				type = "";
				isAutoSearch = true;
			};
			type = type.toLowerCase();
			
			// get plugin or module or pane
			var plugin = null;
			var hasNamespace = (name.indexOf(".") !== -1);
			if (isAutoSearch) {
				try {
					// look for a plugin first
					if (hasNamespace) {
						plugin = eval("$f.ns." + name);
					} else {
						plugin = $f[name];
					};
					
					// look for a module now, if no matching plugin found
					if (!plugin) {
						if (hasNamespace) {
							plugin = eval("$f.modules.ns." + name);
						} else {
							if (!$f.modules) { $f.modules = {}; };
							if (!$f.modules.ns) { $f.modules.ns = {}; };
							plugin = $f.modules[name];
						};					
					};
					
					// look for a pane now, if no matching module found
					if (!plugin) {
						if (hasNamespace) {
							plugin = eval("$f.panes.ns." + name);
						} else {
							if (!$f.panes) { $f.panes = {}; };
							if (!$f.panes.ns) { $f.panes.ns = {}; };
							plugin = $f.panes[name];
						};					
					};					
				} catch (ex) {
					// ignore
				};
			} else {
				// look for plugin or module or pane
				try {
					switch (type) {
						case "module":
							if (hasNamespace) {
								plugin = eval("$f.modules.ns." + name);
							} else {
								if (!$f.modules) { $f.modules = {}; };
								if (!$f.modules.ns) { $f.modules.ns = {}; };
								plugin = $f.modules[name];
							};
							break;
						case "pane":
							if (hasNamespace) {
								plugin = eval("$f.panes.ns." + name);
							} else {
								if (!$f.panes) { $f.panes = {}; };
								if (!$f.panes.ns) { $f.panes.ns = {}; };
								plugin = $f.panes[name];
							};	
							break;
						default:
							if (hasNamespace) {
								plugin = eval("$f.ns." + name);
							} else {
								plugin = $f[name];
							};
							break;
					};
				} catch (ex) {
					// ignore
				};
			};
			
			// check if this is valid reference
			if (!plugin) {
				plugin = null;
			};
			
			// return
			return plugin;
		};
				
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvv FEATURES FUNCTIONALITY  vvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		
		// properties to ignore while merging (these will never be merged)
		var toBeIgnored = "'featureInfo', 'featureHandle', 'featureInclude', 'onFeaturePreInit', 'onFeatureInit', 'onFeatureLoad', 'onParentForward', 'featureConfig', " + 
						  "'include', 'info', 'onPreInit', 'onInit', 'onLoad', 'onReady', 'onUnload', 'onReset', 'onRestart', 'configure', 'onBeforeFeatureAdd', 'onAfterFeatureAdd', ";

		// adds a feature to a target plugin
		// params:
		//	name (string): name of the feature to add
		//	target (string/array): type or name of the plugin to which this feature is to be added
		//				     this could be "root", "app", "page", "master", "view", "module", "pane" OR 
		//					 "any-plugin--or-module-name-with-or-without-namespace" OR an array 
		//				     containing any number of these OR "*", "custom", "system"
		//					 if it is a name, it should be fully qualified in context of $f (without $f prefix)
		//					 E.g., modules.ns.com.vikasburman.Module1 OR ns.com.vikasburman.Plugin1 OR Module1 OR Plugin1
		//					 if it is "page", "master", "view", "pane" or "module", this feature will be added to any already 
		//					 loaded page, master pane or modules and will also be added all future loaded page, master
		//					 panes or modules
		//					 if this is "root" it will be added to framework
		//					 if this is "app" it will be added to app, if available
		//					 if this is some "<plugin-or-module-or-pane--name>", then it will be added if the module or
		//					 pane or plugin is already loaded otherwise it will be added when that plugin or module will be 
		//					 loaded in future 
		//				     if this is "*", it will be added to every plugin and framework root
		//					 if this is "system" it will be added to all system plugins (excluding root)
		//					 if this is "custom" it will be added to all custom plugins
		//	id (string): guid of the feature
		// 	extender (class definition): instance of that is merge-added with plugin object to extend it
		// returns (void): 
		var addFeature = function(name, target, id, extender) {
			// extend, if this is not supressed
			if ($f.config.options.isSupressFeatureExtension) {
				$f.trace("Cannot load feature '" + name + "' because feature extension is currently supressed.");
				return;
			};		

			// handle simulation case
			if (!isEmpty($f.config.options.simulatePackage) && fluidOptions) {
				if ($f.info.version.package.isKernel() && isDefined(fluidOptions.bundledKernelFeatureNames)) { 
					if (fluidOptions.bundledKernelFeatureNames.indexOf("'" + name + "'") === -1) {
						$f.trace("Feature '" + name + "' is not part of kernel package. Skipped loading for simulation.");
						return;
					};
				} else if ($f.info.version.package.isCore() && isDefined(fluidOptions.bundledCoreFeatureNames)) {
					if (fluidOptions.bundledCoreFeatureNames.indexOf("'" + name + "'") === -1) {
						$f.trace("Feature '" + name + "' is not part of core package. Skipped loading for simulation.");
						return;
					};
				};
			};
			
			// check if already added in master list
			var featureItemId = ("_" + id).replace(/-/g, "_"); // prefix with _ because id may start with a number
			if (isDefined($f.vars.features[featureItemId])) {
				$f.trace("Feature id '" + id + "' is already loaded. Cannot re-load.");
				return;
			};

			// inform app about this feature
			var isLoad = true;
			var featureItem = {name: name, target: target, id: featureItemId, extender: extender};
			if ($f.app && isFunction($f.app.onAfterFeatureLoad)) {
				isLoad = $f.app.onBeforeFeatureLoad(featureItem);
			};			

			// process load
			if (isLoad) {
				// add to master list
				$f.vars.features[featureItemId] = featureItem;
			
				// add feature to all matching plugins
				addSpecificFeatureToAllTargets(featureItem);
			
				// inform app about this feature
				if ($f.app && isFunction($f.app.onAfterFeatureLoad)) {
					$f.app.onAfterFeatureLoad(featureItem);
				};
			};
		};

		// adds a specific feature to all target plugins where it may apply
		// this is the case when a new feature is being loaded and it will now be added
		// to all plugins (on which it may be applied)
		// params:
		//	featureItem (object literal): feature item definition
		// returns (void): 	
		var addSpecificFeatureToAllTargets = function(featureItem) {
			// decide where to add
			var plugins = [];
			var targets = [];
			var getFeatureTargets = null;
			var plugin = null;
			var isAddToAllPlugins = false;
			if (isArray(featureItem.target)) {
				targets = featureItem.target;
				if (targets.length === 1 && targets[0] === "*") {
					isAddToAllPlugins = true;
				};
			} else if (targets === "*") {
				isAddToAllPlugins = true;
			} else {
				targets = [featureItem.target];
			};
				
			// in case there are more than one targets, process each target
			$.each(targets, function(i, target) {
				// initialize plugins
				plugins = [];
				
				// find set of plugins for this target
				if (!isAddToAllPlugins) {
					// get feature targets for specific type
					// type is given a precedence over name
					getFeatureTargets = $f.p.plugins.featureTargets[target];
					if (isFunction(getFeatureTargets)) {
						plugins = getFeatureTargets();
					} else {
						// if type not found 
						// assume it as a name
						try {
							plugin = eval("$f." + target);
						} catch (ex) {
							plugin = null;
							$f.error("Target '" + target + "' not found. Cannot add feature '" + name + "'.", false, false, ex);
						};
						if (plugin) {
							plugins.push(plugin);
						};					
					};
				} else {
					plugins = $f.all.plugins("a"); // take all plugins including framework root
				};

				// add feature to each of these plugins
				if (plugins.length > 0) {
					$.each(plugins, function(i, plg) {
						addSpecificFeatureToSpecificTarget(featureItem, plg);
					});
				};
			});
		};

		// adds all features from feature registry which applied to given specific plugin
		// this is the case when a new plugin is being loaded and it will now add all
		// available features (that applies) to it
		// params:
		//	plugin (object): plugin object on which features are to be applied
		// returns (void): 	
		var addAllFeaturesToThisTarget = function(plugin) {
			// decide which all features are to be added to this plugin based on its type and name
			var typeBasedFeatureItems = [];
			var nameBasedFeatureItems = [];
			var targets = [];
			var target = "";
			$.each($f.vars.features, function(i, featureItem) {
				if (isArray(featureItem.target)) {
					targets = featureItem.target;
				} else {
					targets = [featureItem.target];
				};
				$.each(targets, function(i, target) {
					target = $.trim(target);
					if (target === "*") {
						typeBasedFeatureItems.push(featureItem);
					} else {
						if (plugin.handle.type === target) {
							typeBasedFeatureItems.push(featureItem);
						} else if (plugin.handle.qualifiedName === "$f." + target) {
							nameBasedFeatureItems.push(featureItem);
						};
					};
				});
			});
			
			// add all features to this plugin (first type based and then name based)
			if (typeBasedFeatureItems.length > 0) {
				$.each(typeBasedFeatureItems, function(i, featureItem) {
					addSpecificFeatureToSpecificTarget(featureItem, plugin);
				});
			};	
			if (nameBasedFeatureItems.length > 0) {
				$.each(nameBasedFeatureItems, function(i, featureItem) {
					addSpecificFeatureToSpecificTarget(featureItem, plugin);
				});
			};
		};

		// check merge conflicts between plugin and extender objects
		// check to nth level 
		var checkMergeConflicts = function(object, extender, level, levelName, rootObject) {
			var isConflict = false;
			var isProcess = false;
			var name2 = "";
			if (!level) {
				level = 0;
			};
			if (!rootObject) {
				rootObject = extender;
			};		
			$.each(extender, function(name, value) {
				isProcess = true;
				if (level === 0) {
					if (toBeIgnored.indexOf("'" + name + "'") !== -1) {
						isProcess = false;
					} else if (rootObject.featureHandle && rootObject.featureHandle.skipMergingIfDefined) {
						if (rootObject.featureHandle.skipMergingIfDefined.level0 && 
							rootObject.featureHandle.skipMergingIfDefined.level0.indexOf("'" + name + "'") !== -1) {
								isProcess = false;
						};
					};
				} else if (level === 1) {
					if (rootObject.featureHandle && 
						rootObject.featureHandle.skipMergingIfDefined &&
						rootObject.featureHandle.skipMergingIfDefined.level1 && 
						rootObject.featureHandle.skipMergingIfDefined.level1[levelName] && 
						rootObject.featureHandle.skipMergingIfDefined.level1[levelName].indexOf("'" + name + "'") !== -1) {
							isProcess = false;
					};
				};
				if (isProcess) {
					if (isDefined(object[name])) {
						if (isLiteral(object[name]) && isLiteral(value)) {
							level += 1; // going to next level
							isConflict = checkMergeConflicts(object[name], extender[name], level, name, rootObject);
							level -= 1; // back from that level
						} else if (isArray(object[name]) && isArray(value)) {
							// both are array, so it's ok
						} else {
							isConflict = true;
							$f.error("Feature conflict detected at '" + name + "'. Cannot load feature.", false, false);
						};
						if (isConflict) {
							return false; // break
						};
					} else if (name.indexOf("FUNC_") === 0) {
						name2 = name.substring(5); // pick everything after FUNC_
						if (isFunction(object[name2]) && isLiteral(value)) {
							level += 1; // going to next level
							isConflict = checkMergeConflicts(object[name2], extender[name], level, name, rootObject);
							level -= 1; // back from that level
						};
					};
				};
			});

			// return
			return isConflict;
		};

		// merge-extend extender object into plugin object
		// merge-extend to nth level 
		var mergeExtendFeature = function(object, extender, level, levelName, rootObject) {
			var isProcess = false;
			var name2 = "";
			if (!level) {
				level = 0;
			};
			if (!rootObject) {
				rootObject = extender;
			};
			$.each(extender, function(name, value) {
				isProcess = true;
				if (level === 0) {
					if (toBeIgnored.indexOf("'" + name + "'") !== -1) {
						isProcess = false;
					} else if (rootObject.featureHandle && rootObject.featureHandle.skipMergingIfDefined) {
						if (rootObject.featureHandle.skipMergingIfDefined.level0 && 
							rootObject.featureHandle.skipMergingIfDefined.level0.indexOf("'" + name + "'") !== -1) {
								isProcess = !isDefined(object[name]);
						};
					};
				} else if (level === 1) {
					if (rootObject.featureHandle && 
						rootObject.featureHandle.skipMergingIfDefined &&
						rootObject.featureHandle.skipMergingIfDefined.level1 && 
						rootObject.featureHandle.skipMergingIfDefined.level1[levelName] && 
						rootObject.featureHandle.skipMergingIfDefined.level1[levelName].indexOf("'" + name + "'") !== -1) {
							isProcess = !isDefined(object[name]);
					};
				};		
				if (isProcess) {	
					if (isDefined(object[name])) {
						if (isLiteral(object[name]) && isLiteral(value)) {
							level += 1; // going to next level
							mergeExtendFeature(object[name], extender[name], level, name, rootObject);
							level -= 1; // back from that level
						} else if (isArray(object[name]) && isArray(value)) {
							// push items from extender to object
							// since each extender is a new instance, there is no chance of 
							// same item getting into two plugins
							$.each(value, function(i, arrayItem) {
								// push item to object's array
								// this may cause duplicates or conflicts 
								// but that's the best we can do, without knowing anything
								// about the context and any metadata of these items
								object[name].push(arrayItem);
							});
						} else {
							// it's a conflict
							// ideally it will never come here - since conflicts are
							// already checked earlier
							// still log it
							$f.error("Feature conflict detected while extending at '" + name + "'. Feature will be partially loaded.", false, false);
						};
					} else if (name.indexOf("FUNC_") === 0) {
						name2 = name.substring(5); // pick everything after FUNC_
						if (isFunction(object[name2]) && isLiteral(value)) {
							level += 1; // going to next level
							mergeExtendFeature(object[name2], extender[name], level, name, rootObject);
							level -= 1; // back from that level
						};					
					} else {
						// extend
						if (name.indexOf("FUNC_") === 0 && isFunction(object)) {
							object[name.substring(5)] = value; // pick everything after FUNC_ 
						} else {
							object[name] = value;
						};
					};
				};
			});
		};

		// adds a specific feature to given specific plugin
		// params:
		//	featureItem (object literal): feature item definition
		//	plugin (object): plugin object on which feature is to be applied
		// returns (void): 		
		var addSpecificFeatureToSpecificTarget = function(featureItem, plugin) {
			// check if feature is not already added
			var isFailed = isDefined(plugin.handle.features[featureItem.id]);
			if (isFailed) {
				$f.error("Feature '" + featureItem.name + "' is already added to plugin '" + plugin.handle.name + "'. Cannot load.", false, false);
			};			
		
			// check if plugin allows to add this feature
			if (!isFailed && isFunction(plugin.onBeforeFeatureAdd)) {
				isFailed = !(plugin.onBeforeFeatureAdd(featureItem));
			};
		
			// check for conflicts
			var extenderInstance = null;
			if (!isFailed) {
				// create an instance of feature item
				var extender = featureItem.extender;
				extenderInstance = new extender(plugin);

				// check if feature is required to be added
				if (isFunction(extenderInstance.onFeaturePreInit)) {
					if (!extenderInstance.onFeaturePreInit()) {
						isFailed = true;
						$f.trace("Feature '" + featureItem.name + "' decided not to be added to '" + plugin.handle.name + "'. Load skipped.");
					};
				};
				
				// check if all items in this feature are not overwriting any other item
				// if that is the case, it will not add it
				if (!isFailed) {
					isFailed = checkMergeConflicts(plugin, extenderInstance); 
				};
			};

			// include feature include
			if (!isFailed) {
				// define featureHandle, if not defined
				if (!extenderInstance.featureHandle) { extenderInstance.featureHandle = {};	};			
				
				// add feature handle items
				extenderInstance.featureHandle.id = featureItem.id;
				extenderInstance.featureHandle.name = featureItem.name;
				extenderInstance.featureHandle.extender = featureItem.extender;
				extenderInstance.featureHandle.host = plugin;
				extenderInstance.featureHandle.isFeatureIncludeProcessed = false; // flag that is set to true when feature include files are completely processed
				extenderInstance.featureHandle.onFeatureIncludeComplete = function() {
					if (!extenderInstance.featureHandle.isFeatureIncludeProcessed) {
						// mark as processed
						extenderInstance.featureHandle.isFeatureIncludeProcessed = true;
						
						// execute onFeatureInit
						var isFailed = false;
						if (isFunction(extenderInstance.onFeatureInit)) {
							if (!extenderInstance.onFeatureInit()) {
								isFailed = true;
								$f.error("Feature '" + extenderInstance.featureHandle.name + "' failed to initialized for '" + plugin.handle.name + "'. Cannot load.", false, false);
							};
						};
						
						if (!isFailed) {
							// define featureInfo, if not defined
							if (!extenderInstance.featureInfo) { extenderInstance.featureInfo = {};	};

							// define all other version info if not defined and this is a 
							// system or app controlled feature
							if (extenderInstance.featureHandle.isSystemFeature) {
								if (!extenderInstance.featureInfo.version) {
									extenderInstance.featureInfo.version = systemInfo.version;
								};
								if (!extenderInstance.featureInfo.author) {
									extenderInstance.featureInfo.author = systemInfo.author;
								};
								if (!extenderInstance.featureInfo.copyright) {
									extenderInstance.featureInfo.copyright = systemInfo.copyright;
								};
								if (!extenderInstance.featureInfo.web) {
									extenderInstance.featureInfo.web = systemInfo.web;
								};
								if (!extenderInstance.featureInfo.license) { extenderInstance.featureInfo.license = {};	};
								if (!extenderInstance.featureInfo.license.text) {
									extenderInstance.featureInfo.license.text = systemInfo.license.text;
								};	
								if (!extenderInstance.featureInfo.license.url) {
									extenderInstance.featureInfo.license.url = systemInfo.license.url;
								};							
							} else if (extenderInstance.featureHandle.isAppFeature) {
								if (!extenderInstance.featureInfo.version) {
									extenderInstance.featureInfo.version = $f.app.info.version;
								};
								if (!extenderInstance.featureInfo.author) {
									extenderInstance.featureInfo.author = $f.app.info.author;
								};
								if (!extenderInstance.featureInfo.copyright) {
									extenderInstance.featureInfo.copyright = $f.app.info.copyright;
								};
								if (!extenderInstance.featureInfo.web) {
									extenderInstance.featureInfo.web = $f.app.info.web;
								};
								if (!extenderInstance.featureInfo.license) { extenderInstance.featureInfo.license = {};	};						
								if (!extenderInstance.featureInfo.license.text) {
									extenderInstance.featureInfo.license.text = $f.app.info.license.text;
								};	
								if (!extenderInstance.featureInfo.license.url) {
									extenderInstance.featureInfo.license.url = $f.app.info.license.url;
								};						
							};
							
							// add title to feature info (if not defined)
							if (!extenderInstance.featureInfo.title) {
								extenderInstance.featureInfo.title = extenderInstance.featureHandle.name;
							};
							
							// break version into major minor and build
							extenderInstance.featureInfo.version = breakVersionInfo(extenderInstance.featureInfo.version);
							
							// merge extend
							mergeExtendFeature(plugin, extenderInstance);
							
							// add feature into plugin's registry
							plugin.handle.features[extenderInstance.featureHandle.id] = extenderInstance;
							
							// now if plugin is already configured (i.e., loaded) and all batch processing
							// is also done, reconnfigure it because this feature might have added some 
							// members which needs to be processed by other plugins
							// ELSE, it will eventually be configured and then members of this feature (if any)
							// will also be configured
							if ($f.state.isAllBatchLoaded && plugin.handle.isLoad) {
								// get it configured from all other plugins which can configure plugins
								// but since this is being called from feature load scenario
								// it will NOT go and configure other plugins this time
								configurePlugin(plugin, true, true); 
							};

							// execute onFeatureLoad
							if (isFunction(extenderInstance.onFeatureLoad)) {
								extenderInstance.onFeatureLoad();
							};
						
							// let plugin take any other action
							if (isFunction(plugin.onAfterFeatureAdd)) {
								plugin.onAfterFeatureAdd(featureItem);
							};
						};
					};
				};
				
				// initiate include processing
				if (extenderInstance.featureInclude && isArray(extenderInstance.featureInclude)) {
					// special case for kernel-only case
					// since there are NO system features in this case, 
					// therefore send all features to completion directly
					// as in this case includes will not be processed
					if ($f.info.version.package.isKernel()) {
						// directly send for completion, includes can not to be processed
						extenderInstance.featureHandle.onFeatureIncludeComplete();
					} else if ($f.vars.isAssemblyDone) {
						if (!$f.IO) { 
							// if assembly is done and somehow IO is not available
							// and this is an external feature which is being loaded by 
							// inclusion in startup file or somehow
							// directly send it for completion, since includes cannot be processed
							extenderInstance.featureHandle.onFeatureIncludeComplete();			
						} else {		
							if ($f.document.has.feature("fileInclude")) {
								$f.document.includeFeatureFiles(extenderInstance); // (this will end-up in extenderInstance.featureHandle.onFeatureIncludeComplete())
							} else {
								// directly send for completion, includes can not to be processed
								extenderInstance.featureHandle.onFeatureIncludeComplete();
							};
						};
					} else {
						if (!$f.IO) { 
							// add to queue, when IO will be loaded, it will call include for
							// all queued feature instances
							$f.vars.pendingFeatureIncludeFilesQueue.push(extenderInstance);				
						} else {		
							if ($f.document.has.feature("fileInclude")) {
								$f.document.includeFeatureFiles(extenderInstance); // (this will end-up in extenderInstance.featureHandle.onFeatureIncludeComplete())
							} else {
								// directly send for completion, includes can not to be processed
								extenderInstance.featureHandle.onFeatureIncludeComplete();
							};
						};
					};	
				} else {
					// directly send for completion, since there are no include files
					extenderInstance.featureHandle.onFeatureIncludeComplete();
				};
			};
		};

		// check if specified feature is available in given plugin
		var hasFeature = function(name, plugin) {
			var isAvailable = false;
			var nameLC = name.toLowerCase();
			$.each(plugin.all.features(), function(itemName, featureItem) {
				if (featureItem.featureHandle.name.toLowerCase() === nameLC) {
					isAvailable = true;
					return false; // break
				};
			});
			
			// return
			return isAvailable;
		};
		
		// check if specified feature definition is loaded
		var hasFeatureDefinition = function(name) {
			var isAvailable = false;
			var nameLC = name.toLowerCase();
			$.each($f.vars.features, function(name, value) {
				if (value.name.toLowerCase() === nameLC) {
					isAvailable = true;
					return false; // break
				};
			});
			
			// return
			return isAvailable;
		};

		// forward a call to all features which support forward handling
		// params: 
		//	plugin (object): plugin object for which features are to be processed	
		//	forwardName (string): forward name
		//  args (object literal): forward arguments
		// returns (void):
		var forwardCallToFeatures = function(plugin, forwardName, args) {
			$.each(plugin.all.features(), function(name, feature) {
				if (isFunction(feature.onParentForward) && 
					feature.featureConfig && 
					feature.featureConfig.canHandleForwards &&
					feature.featureConfig.canHandleForwards.indexOf("'" + forwardName + "'") !== -1) {
					feature.onParentForward.call(feature, forwardName, args);
				};
			});
		};

		// gets a list of loaded features of given plugin
		// params: 
		//	plugin (object): plugin object for which features are to be loaded	
		// returns (array):	list of features
		var getFeaturesList = function(plugin) {
			var list = [];
			$.each(plugin.handle.features, function(name, feature) {
				list.push(feature);
			});
			
			// return
			return list;	
		};	
		
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvv FRAMEWORK DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
		// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
		// framework handle
		this.handle = {
			// id
			id: "3b6287e3-d59e-482b-a041-2b3f0e108036", 
			
			// name
			name: systemInfo.name,
			
			// alias of plugin
			alias: "",
			
			// name of the file from which framework was loaded
			file: "",
			
			// unique namespace in context of $f or $f.modules or $f.panes, as the case may be 
			namespace: "",			
			
			// fully qualified name 
			qualifiedName: "$f",
		
			// type
			type: "",

			// list of plugin ids which have configured framework
			configuredBy: "",
			
			// if system plugin
			isSystemPlugin: true,
			
			// if app plugin
			isAppPlugin: false,
			
			// basic types checks
			isModule: function() {
				return false;
			},
			isPane: function() {
				return false;
			},				
			isPage: function() {
				return false;
			},
			isView: function() {
				return false;
			},
			isMaster: function() {
				return false;
			},
			isCustom: function() {
				return false;
			},
			isApp: function() {
				return false;
			},
			isSystem: function() {
				return false;
			},
			isRoot: function() {
				return true;
			},	
			
			// flag that is set to true when plugin include files are completely processed
			isIncludeProcessed: false,
			
			// flag that is set to true when plugin's resources which are loaded async are processed
			isResourcesProcessed: false,			

			// flag that is set to true when plugin onInit is called and it was successful
			isInit: false,			
			
			// flag that is set to true when plugin onLoad is called
			isLoad: false,
			
			// flag that is set to true when plugin onReady is called
			isReady: false,
			
			// a check flag that is used by setInterval call
			checkFlag: null,
			
			// called when plugin include files are completely processed
			onIncludeComplete: function() {
				// it's init was already called, so no need to call from here
				
				// it's configure, onLoad and onReady will be called in batch
				// after everything is loaded, so don't need to call from here
				
				// perform include flag processing
				if (!$f.handle.isIncludeProcessed) {
					// set flag
					$f.handle.isIncludeProcessed = true;
					
					// add trace message
					var completeName = ""
					if (isEmpty($f.handle.namespace)) {
						completeName = $f.handle.name;
					} else {
						completeName = $f.handle.namespace + "." + $f.handle.name;
					};
					$f.trace("Plugin '" + completeName + "' is initialized. Init: " + $f.handle.isInit.toString() + ", Load: " + $f.handle.isLoad.toString() + ", Ready: " + $f.handle.isReady.toString() + ".");
				};
			},
			
			// features that are added to framework root
			features: {}
		};
		
		// framework info
		this.info = {
			// title of the framework
			title: systemInfo.title,
			
			// version of the framework (major.minor.build)
			version: systemInfo.version,
			
			// author of the framework
			author: systemInfo.author,
			
			// copyright notice
			copyright: systemInfo.copyright,
			
			// detailed description of the framework
			description: systemInfo.desc,
			
			// web url of the framework
			web: systemInfo.web,
			
			// license of the framework
			license: {
				text: systemInfo.license.text,
				url: systemInfo.license.url
			}
		};
			
		// host 
		this.host = null;

		// pre-initialization handler
		// returns (void): 
		this.onPreInit = function() { 
			// just for consistency with other plugins
			// not required in this case
		};
	
		// initialization handler
		// returns (void): 
		this.onInit = function() { 
			// return if already initialized
			if ($f.handle.isInit) {
				return;
			};

			// check availability of required browser support
			if (!isDefined(window.$)) { $f.error("jQuery library must be loaded before " + $f.handle.name + ". Cannot continue.", true, true); };
			if (!isDefined(window.$.doTimeout)) { $f.error("jQuery's doTimeout plugin library must be loaded before " + $f.handle.name + ". Cannot continue.", true, true); };

			// set its type
			$f.handle.type = $f.p.plugins.types.root;

			// update fluidOptions from queryString 
			// (this is to support to handle some special cases, generally would not be required)
			// this is available only if isAllowDynamicFluidOptions is set to true at design time
			if ($f.config.options.isAllowDynamicFluidOptions) {
				var vars = $f.p.getQueryStrings();
				var value = null;
				if (!isDefined(fluidOptions)) { window.fluidOptions = {}; } 
				$.each(vars, function(i, name) {
					// don't consider changing isAllowDynamicFluidOptions itself
					if (name !== "isAllowDynamicFluidOptions") {
						// overwrite fluidOptions value with custom evaluation
						// NOTE: Only bool, string and number values are supported at the moment
						value = vars[name];
						if (value.toLowerCase() === "true") { fluidOptions[name] = true; } 
						else if (value.toLowerCase() === "false") { fluidOptions[name] = false; }
						else if (!isNaN(Number(value))) { fluidOptions[name] = Number(value); }
						else { fluidOptions[name] = value; };
					};
				});
			};
			
			// update version from defined build time information
			if (fluidOptions && fluidOptions.fluidVersion) {
				systemInfo.version = fluidOptions.fluidVersion.split(";")[0].split("=")[1]; // read x.y.z from version=x.y.z; ... string
			};

			// update fixedPluginNames from defined build time information
			if (fluidOptions && fluidOptions.bundledFixedPluginNames) {
				fixedPluginNames += fluidOptions.bundledFixedPluginNames;
			};
		
			// initialize configuration using fluidOptions variable if exists
			if (fluidOptions) {
				// update every value from fluidOptions to here
				$.each(fluidOptions, function(name, value) {
					if (isDefined($f.config.options[name])) {
						$f.config.options[name] = value;
					} else {
						// seems additional information
						// push it inside custom
						$f.config.options.custom[name] = value;
					};
				});
			};
			
			// other initialization
			$f.host = window;
			
			// framework version info processing
			$f.info.version = breakVersionInfo($f.info.version);
			if (fluidOptions && fluidOptions.fluidVersion) {
				var fluidVersionParts = fluidOptions.fluidVersion.split(";");
				$f.info.version.raw = fluidOptions.fluidVersion;
				$.each(fluidVersionParts, function(i, item) {
					var itemParts = item.split("=");
					$f.info.version[$.trim(itemParts[0])] = $.trim(itemParts[1]);
				});
			};
			// update package information
			if (!$f.info.version.package) {
				$f.info.version.package = { type: "" };
			} else {
				var pkg = $f.info.version.package;
				if (isEmpty($f.config.options.simulatePackage)) {
					$f.info.version.package = { type: pkg };
				} else {
					if ($f.config.options.simulatePackage.toLowerCase() === "kernel") {
						$f.info.version.package = { type: $f.vars.packages.Kernel + " (Simulated)" };
					} else if ($f.config.options.simulatePackage.toLowerCase() === "core") {
						$f.info.version.package = { type: $f.vars.packages.Core + " (Simulated)" };
					} else {
						$f.info.version.package = { type: pkg };
					};
				};
			};
			$f.info.version.package.isKernel = function() { 
				return ($f.info.version.package.type.toLowerCase() === $f.vars.packages.Kernel.toLowerCase() || $f.config.options.simulatePackage.toLowerCase() === "kernel"); 
			};
			$f.info.version.package.isCore = function() { 
				return ($f.info.version.package.type.toLowerCase() === $f.vars.packages.Core.toLowerCase() || $f.config.options.simulatePackage.toLowerCase() === "core"); 
			};
			$f.info.version.package.isCustom = function() { 
				return ($f.info.version.package.type.toLowerCase() === $f.vars.packages.Custom.toLowerCase()); 
			};
			$f.info.version.package.isFull = function() { 
				return ($f.info.version.package.type.toLowerCase() === $f.vars.packages.Full.toLowerCase()); 
			};
			$f.info.version.package.isSimulating = function() { 
				return (!isEmpty($f.config.options.simulatePackage)); 
			};
			
			// identify current deployment mode
			$f.vars.currentDeploymentMode = $("html").attr("deploymentMode");
			if (!isDefined($f.vars.currentDeploymentMode)) {
				$f.vars.currentDeploymentMode = $f.vars.deploymentModes.portableApp; // default
			};

			// special case overrides for local file system access support
			if ($f.info.version.package.isKernel()) {
				// in case of Kernel package, not enough functionality is added which can
				// handle the local file system access, therefore turn it off irespective of
				// external setting
				$f.config.options.isEnableLocalFileSystemAccess = false;
			} else if ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.portableApp.toLowerCase()) {
				// in case of any other package, but portableApp mode, local file system access
				// is a must, therefore turn it on irespective of external setting
				$f.config.options.isEnableLocalFileSystemAccess = true;
			};
			
			// add browser event handlers			
			// onLoad vs ready -- both works equally well
			//$(window).load(function() { onLoad(); });
			$(document).ready(function() { onLoad(); });
			
			// others
			$(window).unload(function() { onUnload(); });
			$(window).bind("online offline", function(event) { onOnLineOffLine(); });	
			$(window).bind("error", function(message, url, lineNumber) { return onError(message, url, lineNumber); });
			$(window).bind('hashchange', function(){ onHashChange() });
			
			// forward to features
			$f.forwardToFeatures("onInit"); 
			
			// set flag
			$f.handle.isInit = true; // this actually has no meaning (have it just for the sake of consistency), because if there would be error, it will be thrown from above method
		};
		
		// load handler
		// returns: (void)
		this.onLoad = function() { 
		};

		// ready handler
		// returns: (void)
		this.onReady = function() {
			// add powered-by logo (at the bottom-right corner)
			// this is binary version of fluid/images/crafted-on-fluid.png file - that file is left for someone to use as required
			// but image is added using this binary version
			if ($f.env && !$f.config.options.isHideFrameworkLogo) {
				var element = null;
				if ($f.env.has.feature("structuralElements")) {
					element = $("#" + $f.env.container.host());
				} else {
					element = $("body");
				};
				var binaryDataOfPoweredByFluidLogo = "";
				element.append('<div style="text-align: right;" title="' + $f.info.title + " - " + $f.info.version.version + " (" + $f.info.version.name + ")" + '"><a href="' + $f.info.web + '" target="_blank"><img src="' + binaryDataOfPoweredByFluidLogo + '" style="border: none;"/></a></div>');
			};
		};
		
		// unload handler
		// returns: (void)
		this.onUnload = function() {
		};
		
		// reset handler
		// returns: (void)
		this.onReset = function() {
		};
		
		// restart handler
		// returns: (void)
		this.onRestart = function() {
		};
		
		// configure given plugin 
		// this is called for each plugin if canConfigurePlugins is set to true
		// params:
		//	plugin (object): plugin object to configure
		//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
		//                                        this plugin otherwise should also be done now with
		//                                        this plugin, because this is being loaded after all
		//                                        batch processing is done at load time
		//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
		// 										    a new feature is added to plugin which may have added
		//											some members those required reconfiguration		
		// returns (void):	
		this.configure = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {
		};
		
		// forward a call to all features which support forward handling
		// params: 
		//	forwardName (string): forward name
		//  args (object literal): forward arguments
		// returns (void):
		this.forwardToFeatures = function(forwardName, args) {
			// forward 
			forwardCallToFeatures($f, forwardName, args);
		};
		
		// plugin configuration
		this.config = {
			// key using which time at which refresh was started is stored in session
			refreshStartedAtSessionKey: "__root__refreshStartedAt",	

			// zIndex of the plugin controls the sequence of calling
			// onLoad, onReady and onUnload handlers of the plugins
			// with respect to each other
			// valid values are between 0 to 99999. Values between 0 to 9999
			// and 90001 upwards are reserved for framework plugins. 
			// For custom plugins use any value between 10000 to 90000.
			zIndex: 0,
			
			// can this plugin configure other plugins
			// if this is set to true, after plugins are initialized, these will be
			// given to this plugin's configure method to do required configuration
			canConfigurePlugins: false,
			
			// framework options object (it's values can be updated via already existing fluidOptions variable)
			options: {
				// any custom options can be defined here-under
				custom: { 
				
				},
				
				// if fluidOptions overrides can be provided dynamically 
				// via query string
				isAllowDynamicFluidOptions: true,
				
				// if it should run in debug mode
				isDebug: false,
				
				// master switch to control trace log
				isTrace: false,			
		
				// if write to browser console
				isWriteToConsole: true,
				
				// data store 
				// where databases are stored. Possible values are:
				// 	local: when databases are stored under local %DATA%/<dbName> folder
				//	server: when databases are stored on developer's server and can be reached via 
				//          defined services
				//			(TODO: where server config is defined - to be devised)
				//	dropbox: when databases are stored in end-user's dropbox and can be reached via
				//           dropbox API
				//			 (TODO: where dropbox config is defined - to be devised)
				dataStore: "local",
				
				// local data storage prompt dialog url
				// url (html) that contains the message that user will be prompted with when application is being 
				// served from a web server but since data is always stored locally, it asks for local data store 
				// folder
				// this url should return a value in following format:
				// {dataFolder: <complete folder name>, ttl: <minutes>}
				// this file is assumed to be in configured app root folder
				// it is changed in build script
				localDataPrompt: "",
			
				// if logging is to be supressed
				// logging is an expensive operation, so except in debug mode, it should remain supressed
				isSupressLogging: false,			
				
				// if alerts are to be supressed
				isSupressAlerts: false,
				
				// if body element should not be set to show automatically
				isSupressAutoBodyVisible: false,
				
				// if stop throwing errors
				isSupressThrowErrors: false,
				
				// if show all errors as alert in debug mode
				isShowAllErrorsInDebugMode: false,
				
				// if stop loading plugin extensions (plugins)
				isSupressPluginExtension: false,
				
				// if html nuggets processing is to be supressed
				isSupressProcessingHtmlNuggets: false,
				
				// if stop loading feature extensions (features)
				isSupressFeatureExtension: false,				
				
				// if hide crafted on fluid logo
				isHideFrameworkLogo: false,
				
				// if a tear-down package mode is to be simulated
				// (empty), if not to be simulated
				// "kernel", if kernel package mode is to be simulated
				// "core", if core package mode is to be sumulated
				simulatePackage: "", 
				
				// what extension to be recognized as a page extension
				// in routes (i.e, # part of it)
				pageExtensionInUrl: "page",
				
				// what extension to be recognized as a pane extension
				// in routes (i.e, # part of it, when plugin is being loaded via fluid:// protocol
				paneExtensionInUrl: "pane",
				
				// what extension to be recognized as a plugin extension
				// in routes (i.e, # part of it, when plugin is being loaded via fluid:// protocol
				pluginExtensionInUrl: "plugin",

				// what extension to be recognized as a module extension
				// in routes (i.e, # part of it, when plugin is being loaded via fluid:// protocol
				moduleExtensionInUrl: "module",
				
				// what extension to be recognized as a feature extension
				// in routes (i.e, # part of it, when plugin is being loaded via fluid:// protocol
				featureExtensionInUrl: "feature",

				// what extension to be recognized as a command function extension
				// in routes (i.e, # part of it, when command function is being loaded via fluid:// protocol
				commandExtensionInUrl: "cmd",
				
				// what extension to be recognized as a function extension
				// in routes (i.e, # part of it, when function is being called via fluid:// protocol
				functionExtensionInUrl: "func",
				
				// if enable access to local file system in a web deployment scenario
				// for portable deployment scenario, this remains turned on - irrespective of this setting
				// if turned on, this may require installing java plugin for the browser and user may have
				// to allow on some security warnings before it can work
				// the matrix for needing Java wrt browser and operating mode, goes as:
				// MODE                | FS required |     IE     |    FireFox    | Chrome   |  Safari
				// -----------------------------------------------------------------------------------------
				// portable            |   Yes        |     No     |      Yes      |  Yes     |    Yes
				// web                 |   Yes        |     Yes    |      Yes      |  Yes     |    Yes
				// web                 |   No         |     No     |      No       |  No      |    No
				// web (Low Security)  |   Yes        |     No     |      Yes      |  Yes     |    Yes
				// ------------------------------------------------------------------------------------------
				// if this is turned off, all file system access (including read and write) operations
				// will stop working. 
				// Some framework plugins (cache and states) use local file system as 
				// fallback to missing browser capabilities such as sessionStorage, localStorage etc. Therefore 
				// in those cases, a new version of browser should be used in case fallback to local session store 
				// (which falls back to Window.name) is turned off because of planned heavy data usage of cache 
				// and/or states.
				// Some framework plugins (DB and logger) exclusively works with local file system. Therefore 
				// if this is turned off, these plugins will not be loaded, unless a custom version is configured 
				// which can deal with this scenario.
				// Some framework plugins (Configuration) which works with local file system for some enhanced
				// functionality will work partially. E.g., configuration will only read config file but will
				// not allow to save it
				isEnableLocalFileSystemAccess: true,
		
				// based on browser/os requirements of the application the inbuilt order (as comma delimited list of strings) 
				// can be changed here. By default the order is created dynamically  based on known browser support 
				// and operation mode of the application. However that can be overridden by defining a static
				// order here. If this is empty, inernal dynamic order will be used
				// possible driver names are: 
				// "fsa" - Uses fluid's fsa.jar (requires Java plugin for browser) [stable, least intrruptions, wide browser support]
				// "XPConnect" - Uses FireFox XPConnect API [stable, least intrruptions, very limited browser support]
				// "fso" - Uses IE's FileSystemObject [stable, several intrruptions, very limited browser support]
				fileSystemDriversCustomOrder: "",
		
				// if this is enabled and file system is not enabled, plugins (such as cache and states)
				// do fallback to session store as store for storing temp data
				isFallbackToSessionStoreWhenNoFileSystem: true,
				
				// if local data folder location is to be asked in a modal dialog
				// this applies in a non-portableApp 
				isAskLocalDataFolderInModalDialog: true,
				
				// file extensions which are supposed to get dynamically generated html from server
				// dynamic html can either be a layout or a template.
				// including files (via Include) having these extensions will always cause these to be 
				// fetched from server
				// In order to ensure that cuch files are not copied in portableApp file set, this same
				// set should also be defined at SERVER_ONLY_FILE_TYPES in buildOptions which is a super-set
				// for such file types
				// format of this string should be .<ext1>;.<ext2>;...;
				// Note the trailing ; and no spaces in between
				dynamicHtmlEndPoints: ".asp;.aspx;.jsp;.php;.cgi;.pl;",

				// start block for a DOM element which is used to wrap
				// a html template
				// it must have %NAME% placeholder which will be replaced
				// by the templateName at runtime
				htmlTemplateElementDOMWrapperStart: "<script type='text/html' id='%NAME%'>",
				
				// end block for a DOM element which is used to wrap
				// a html template
				htmlTemplateElementDOMWrapperEnd: "</script>",
				
				// master layout container element id in host html - to hold master page layout
				// this element would generally be defined inside host layout html (it can also be redefined in app config)
				masterContainerElementId: "master",
				
				// page layout container element id in master layout html - to hold page layout
				// this element would generally be defined inside master layout html (it can also be redefined in master page config)
				pageContainerElementId: "page",		

				// views layout container element id in page layout html - to hold views layouts
				// this element would generally be defined inside page layout html (it can also be redefined in page config)
				viewsContainerElementId: "views",	
				
				// page's main content container element id in page layout html - to hold most important content of the page
				// this element would generally be defined inside page/view layout html (it can also be redefined in page/view config)
				mainContentContainerElementId: "content",
				
				// progressive page content container element id in page layout html - to hold progressively appearing content of the page
				// this element would generally be defined inside page layout html (it can also be redefined in page config)
				progressivePageContentContainerElementId: "progressive_content",
				
				// breadcrumbs container element id in page layout html - to hold bread crumbs for page
				// this element would generally be defined inside page layout html (it can also be redefined in page config)
				breadCrumbsContainerElementId: "breadcrumbs",				

				// wizard container element id in page layout html - to hold wizard steps in a page
				// this element would generally be defined inside page layout html (it can also be redefined in page config)
				wizardContainerElementId: "wizard",	
				
				// loading animation element - for holding UI of loading animation
				// if this is not empty, once navigation is complete display: none will be set for this
				// if this is empty, nothing will be done
				loadingElementId: "loadingBar", 
			
				// reconfigure named plugins of the framework
				// provide an alternate implementation for required ones by giving the JS file name for a named plugin, 
				// leave it empty if inbuilt version of the plugin is to be used
				// in case inbuild plugin is not required - use "off" keyword (use with care, framework may stop working)
				namedPlugins: {
					// with the help of fluidOptions, any system plugin can be turned off 
					// or an external version can be configured
				},
				
				// default page url of the application
				// it is generally defined in application plugin, however in cases where app plugin
				// is not being used, it can be defined here. If defined in app plugin that will take
				// precedence
				defaultPageUrl: "", 
				
				// name of the temp folder where plugins can create temporary files
				// if this is not defined, it will assumed to be "temp"
				// it is always in relation to data folder
				tempFolder: "temp",

				// name of the folder where fluid system and dependencies placed under
				// if this is not defined, it will assumed to be "fluid",  although when using
				// build engine, it is taken care of by build engine as per build-time definition
				fluidFolder: "fluid",
				
				// name of the folder where application is placed under
				// if this is not defined, it will assumed to be "app", although when using
				// build engine, it is taken care of by build engine as per build-time definition
				appFolder: "app",			
				
				// name of the folder where application data is placed under
				// if this is not defined, it will assumed to be "data"
				// although this can be defined in app config file as well - which will take precedence if defined
				dataFolder: "data",

				// name of the resources folder where plugin resources are placed under locale specific sub-folders
				// if this is not defined, it will assumed to be "res" inside app folder
				resourcesFolder: "%APP%/res",		
				
				// name of the external config JSON file 
				// this is always assumed to be inside data folder
				// though its master copy must be present in app folder
				configJSON: "",
				
				// name of the startup html, it is changed in build script
				// this is used when page is served directly from default url
				// this should always match to the default page set on the server
				startupHtml: "",
				
				// name of the 404 html, to show when page navigation fails
				// it is changed in build script
				error404Html: "",				
				
				// error message container element in error404Html - for holding navigation error 
				errorMessageElementId: "error", 	
				
				// minimum java version that is required for file system access java applet 
				// to work. 
				minJavaVersion: "1.7+",
				
				// where to go to download java runtime
				javaInstallerUrl: "http://java.com/en/download/manual.jsp"
			}
		};
		
		// framework state (contents here-in must be JSON serializable)
		// if items are defined here, these will be preserved across page refresh (by 
		// serializing/deserializing transparently)
		this.state = {
			// if application is restarting (this is preserved only during load process, as soon as UI is loaded completely 
			// it is set back to false. Since a UI load causes complete document load, it is defined as state variable)
			isAppRestarting: false,
			
			// if application is restarting or refreshing and wheather loadAll for states, resources, etc. for all plugins is called or not 
			// (this is preserved only during load process, as soon as UI is loaded completely 
			// it is set back to false. Since a UI load causes complete document load, it is defined as state variable)
			isAllBatchLoaded: false,
			
			// if application is restarting or refreshing and wheather onReady for all plugins is called or not 
			// (this is preserved only during load process, as soon as UI is loaded completely 
			// it is set back to false. Since a UI load causes complete document load, it is defined as state variable)
			isAllBatchReady: false
		};

		// all namespace based plugins will be loaded here under
		this.ns = { 
		};
		
		// framework variables
		// value of these variables is NOT maintained across page refresh
		this.vars = {
			// a place where flags, for plugins for which external version is
			// being loaded, are added
			// used by extend method
			lookingForExternalVersionOf: { },
			
			// if assembly of framework is done
			isAssemblyDone: false,
			
			// types of packages
			packages: {
				// only infrastructure
				Kernel: "Kernel",
				
				// Kernel + core functionality of framework
				Core: "Core",
				
				// Kernel + Core + plugins/features of choice
				Custom: "Custom",
				
				// Everything, Excluding plugins/features of choice
				Full: "Full"
			},
			
			// types of available deployment options
			deploymentModes: {
				// portable app - when application is running from filesystem e.g., from flash drive (usb)/ harddisk on desktop
				//                this is the most preferred approach and the USP of this framework
				// approach:
				//	- generally hosted on web as zipped file 
				//	- installation is manual - but as simple as extract zip content and ready to go
				//  - optionally an installation setup can be created - but that will give a feel that this has some dependencies etc. 
				//	- configured to be served from filesystem
				//	- update process is totally manual unless some non-html based programatic support is added and deployed 
				//	- define html tag in startup html as: 
				//	  * <html deploymentMode="portableApp">
				//	- data is stored locally at user defined location
				portableApp: "portableApp",
				
				// wrapped app - when application is running wrapped inside another app, 
				//               generally native app such as windows 8 app, android app or iPhone app
				// approach:
				//	- generally hosted on web as zipped file 
				//	- installation is via app store 
				//	- update process is via store 
				//	- define html tag in startup html as: 
				//	  * <html deploymentMode="wrappedApp" wrapper="win8|android|ios">
				//	- data is stored locally at default app location
				wrappedApp: "wrappedApp",
				
				// offline app - when application is running in complete offline mode
				// approach:
				//	- hosted on web
				//  - configured to be downloaded to appcache and then served from appcache
				//	- with the help of updated appcache manifest, application updates can be pushed from server 
				//	- define html tag in startup html as: 
				//	  * <html deploymentMode="offlineApp" manifest="web.appcache">
				//	- add following files on root folder:
				//	  * web.appcache -- having list of *all* files of the application
				//	  * web.config -- having default html setting
				//	- data is stored locally at user defined location
				offlineApp: "offlineApp",

				// cws hosted app - when application is published on chrome web store as hosted app
				// approach:
				//	- hosted on web
				//  - configured to be downloaded to appcache and then served from appcache
				//  - published on chrome web store as hosted app
				//	- with the help of updated appcache manifest, application updates can be pushed from server 			
				//	- define html tag in startup html as: 
				//	  * <html deploymentMode="cwsHostedApp" manifest="web.appcache">
				//	- add following files on root folder:
				//	  * web.appcache -- having list of *all* files of the application
				//	  * web.config -- having default html setting				
				//	- create and include chrome web store hosted app manifest
				//	- data is stored locally at user defined location
				cwsHostedApp: "cwsHostedApp",

				// online app - when application is running in complete online mode
				//              although this mode is supported, this framework is not made for this type of apps
				// approach:
				//	- hosted on web
				//	- define html tag in startup html as: 
				//	  * <html deploymentMode="onlineApp">
				//	- add following file on root folder:
				//	  * web.config -- having default html setting
				//	- data is stored locally at user defined location
				onlineApp: "onlineApp"
			},
			
			// loaded plugins list
			plugins: [],
			
			// sorted list cache 
			pluginsSortedList: {
				ascending: null,
				descending: null
			},
			
			// loaded features repository
			features: {},
			
			// list of plugins by name
			pluginsNamedList: [],
			
			// trace log
			traceLog: [],
			
			// queue of plugins which are loaded
			// before IO is loaded
			pendingIncludeFilesQueue: [],
			
			// queue of features which are loaded
			// before IO is loaded
			pendingFeatureIncludeFilesQueue: [],
			
			// interval in milliseconds that is used in setInterval for on load processing
			// this controls that document.ready processing is waiting till all system plugins are initialized
			allPluginInitCheckInterval: 1,
			
			// holds current deployment mode
			currentDeploymentMode: "",

			// if temporary supress showing errors as messages in debug mode
			isSupressShowingErrorOnce: false
		};
		
		// current deployment mode
		// returns (string): deployment mode setting
		this.deploymentMode = function() {
			// return
			return $f.vars.currentDeploymentMode;
		};

		// is portable deployment
		// returns (boolean): true/false
		this.deploymentMode.isPortable = function() {
			return ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.portableApp.toLowerCase());
		};
		
		// is wrapped deployment
		// returns (boolean): true/false
		this.deploymentMode.isWrapped = function() {
			return ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.wrappedApp.toLowerCase());
		};
		
		// is online deployment
		// returns (boolean): true/false
		this.deploymentMode.isOnline = function() {
			return ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.onlineApp.toLowerCase());
		};
		
		// is offline deployment
		// returns (boolean): true/false
		this.deploymentMode.isOffline = function() {
			return ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.offlineApp.toLowerCase());
		};
		
		// is cwsHosted deployment
		// returns (boolean): true/false
		this.deploymentMode.isCWSHosted = function() {
			return ($f.vars.currentDeploymentMode.toLowerCase() === $f.vars.deploymentModes.cwsHostedApp.toLowerCase());
		};
			
		// all strcuture
		this.all = {
			// get a list of all plugins loaded so far
			// params:
			//	sortType (string): ) Optional. what type of sorting is required
			//					   sorting is done based on configured z-Index of plugin
			// 					   0 - 9999 is reserved for system plugins
			// 					   10000 - 90000 range is for custom plugins
			// 					   90001 - 99999 range is again reserved for system plugins		
			//					   <empty>: None
			//					   "A": Ascending sort (default)
			//					   "D": Descending sort
			// returns (array): 
			plugins: function(sortType) {
				if (sortType) {
					sortType = sortType.toLowerCase();
				} else {
					sortType = "a";
				};
				
				// return, if available in cache
				var zIndexedList = [];
				if (sortType === "a" && $f.vars.pluginsSortedList.ascending) {
					zIndexedList = $f.vars.pluginsSortedList.ascending;
				} else if (sortType === "d" && $f.vars.pluginsSortedList.descending) {
					zIndexedList = $f.vars.pluginsSortedList.descending;
				} else {
					// update cache for required type
					zIndexedList = zIndexedList.concat([$f], $f.vars.plugins);
					switch(sortType) {
						case "a": 
							zIndexedList.sort(function(a, b) {
								return (a.config.zIndex - b.config.zIndex);
							});
							$f.vars.pluginsSortedList.ascending = zIndexedList;
							break;
						case "d":
							zIndexedList.sort(function(a, b) {
								return (b.config.zIndex - a.config.zIndex);
							});		
							$f.vars.pluginsSortedList.descending = zIndexedList;
							break;
					};
				};
				
				// return
				return zIndexedList;
			},
			
			// get a list of all features loaded so far
			// returns (array): 
			featureDefinitions: function() {
				var ftrs = [];
				var allFeatureDefinitions = $f.vars.features;
				$.each(allFeatureDefinitions, function(name, value) {
					ftrs.push(value);
				});
				
				// return
				return ftrs;
			},

			// gets an array of all loaded features in framework
			// returns (array): features list
			features: function() {
				// return
				return getFeaturesList($f);
			}
		};

		// get a list of all system plugins loaded so far
		// returns (array): 
		this.all.plugins.system = function() {
			var systemPlugins = [];
			$.each($f.all.plugins(), function(i, plugin) {
				if (plugin.handle.isSystem()) {
					systemPlugins.push(plugin);
				};
			});
			
			// return
			return systemPlugins;
		};
		
		// get a list of all custom plugins loaded so far
		// returns (array): 
		this.all.plugins.custom = function() {
			var customPlugins = [];
			$.each($f.all.plugins(), function(i, plugin) {
				if (plugin.handle.isCustom()) {
					customPlugins.push(plugin);
				};
			});
			
			// return
			return customPlugins;
		};
		
		// get structure
		this.get = {
			// finds the already loaded plugin and returns its instance
			// params:
			//	name (string): name of the plugin to look for
			//	               if plugin has namespace in it, it should be part of this string
			// return (object): returns plugin object if success, null otherwise	
			plugin: function(name) {
				// forward
				return getPlugin(name); // don't pass false, false; then only it will switch to autoSearch mode
			}
		};
		
		// finds the already loaded plugin by its id and returns its instance
		// params:
		//	pluginId (string): id of the plugin
		// return (object): returns plugin object if success, null otherwise	
		this.get.plugin.byId = function(pluginId) {
			// look for plugin by id
			var plugin = null;
			$.each($f.vars.plugins, function(i, p) {
				if (p.handle.id === pluginId) {
					plugin = p;
					return false; // break
				};
			});

			// return
			return plugin;
		};

		// finds the already loaded plugin by its qualified name and returns its instance
		// params:
		//  qualifiedPluginName (string): complete qualified plugin name with namespace (e.g., com.microsoft.aop)
		//  type (string): type of plugin
		//				   "pane", "module", "plugin", "" (empty means "plugin")
		// return (object): returns plugin object if success, null otherwise	
		this.get.plugin.byQualifiedName = function(qualifiedPluginName, type) {
			// look for plugin by qualified name
			var plugin = null;
			var pluginPath = "";
			var hasNamespace = (qualifiedPluginName.indexOf(".") !== -1);
			if (type === "module") {
				if (hasNamespace) {
					pluginPath = "$f.modules.ns." + qualifiedPluginName;
				} else {
					pluginPath = "$f.modules." + qualifiedPluginName;
				};
			} else if (type === "pane") {
				if (hasNamespace) {
					pluginPath = "$f.panes.ns." + qualifiedPluginName;
				} else {
					pluginPath = "$f.panes." + qualifiedPluginName;
				};					
			} else {
				if (hasNamespace) {
					pluginPath = "$f.ns." + qualifiedPluginName;
				} else {
					pluginPath = "$f." + qualifiedPluginName;
				};
			};
			
			// eval
			try {
				plugin = eval(pluginPath);
			} catch (ex) {
				// ignore
			};

			// return
			return plugin;
		};

		// has strcuture
		this.has = {
			// check if specified plugin is available in framework
			// params: 
			//	name (string): name of the plugin to check
			//	               if plugin has namespace in it, it should be part of this string
			// returns (boolean): true, if available, false otherwise
			plugin: function(name) {
				// return 
				return (!isNull($f.get.plugin(name)));
			},
			
			// check if specified feature is available in framework
			// params: 
			//	name (string): name of the feature to check
			// returns (boolean): true, if available, false otherwise
			feature: function(name) {
				// return 
				return hasFeature(name, $f);
			},

			// check if specified feature definition is loaded
			// params: 
			//	name (string): name of the feature to check
			// returns (boolean): true, if available, false otherwise
			featureDefinition: function(name) {
				// return 
				return hasFeatureDefinition(name);
			},			
		};
				
		// executes arbitrary javascript function
		// params:
		// 	func (string/func): func name or function to execute
		// 	args (array): optional. arguments to pass, if any (applicable only when it is function name)
		// return (void):
		this.exec = function(func, args) {
			// create script to run
			if (isString(func)) {
				var cmd = func + "(";
				var isFirst = true;
				if (args) {
					$.each(args, function(i, value) {
						if (!isFirst) {
							cmd = cmd + ", ";
							isFirst = false;
						};
						cmd = cmd + "args[" + i.toString() + "]";
					});
				};
				cmd = cmd + ")";
				
				// run
				try {
					eval(cmd);
				} catch (ex) {
					$f.error("Failed to execute func '" + func + "'.", false, false, ex);
				};
			} else if (isFunction(func)) {
				// run
				try {
					func();
				} catch (ex) {
					$f.error("Failed to execute given func.", false, false, ex);
				};
			} else {
				// ignore
			};
		};
		
		// execute given function after specified millseconds
		// params:
		//	func (string/function): func name or function to execute after some delay
		//	afterMS (number): milliseconds delay
		// 	args (array): optional. arguments to pass, if any (applicable only when it is function name)
		// returns (void):
		this.exec.withDelay = function(func, afterMS, args) {
			// take default delay, if not defined
			if (!isNumber(afterMS)) { afterMS = 2 };
			
			// set to execute
			setTimeout(function() { $f.exec(func, args); }, afterMS);
		};
		
		// extend framework root
		// params:
		// 	type (string): plugin type. Possible values are:
		//                 app, page, master, view, module, pane, feature, system and custom
		//                 if not specified or incorrect, it will be treated as custom
		//				   it can also be name of a plugin that needs to be extended
		//	name (string): name of the plugin 
		//                 name can contain namespace using . notations, E.g.,
		//                 com.microsoft.office.word, in this case "word" would be the
		//                 plugin name and "com.microsoft.office" will be the namespace
		//				   this is allowed only for custom or module types
		//                 if type defines name of a plugin which needs to be extended, this
		//                 needs to be the name of the method which will be called for extension
		//				   rest all can be parameters of that method
		//	alias (string): a unique 2 to 4 characters alias for the plugin
		//                  this might be required only for most used plugins
		//                  can be used only with non-namespaced and non-module type custom plugins
		//				    In case type is "feature", this is the target (type {root, app, page, master, view, module} 
		//					or name {exact name of the plugin with or without namespace}) plugin to which this 
		//					feature will be added. In case of specific module, it should be prefixed with modules.
		//				    E.g., modules.Module1 or modules.ns.com.microsoft.word
		//				    Note: This could also contain multiple target names (comma delimited) if same 
		//					feature is to be added to multiple targets
		//                  It can also has "*" to mention that this needs to be added to all plugins
		//	id (string): guid of the plugin
		// 	extender (class definition): instance of that is merge-updated with plugin object to extend it		
		// return (object): returns extended plugin object if success, null otherwise		
		//                  if there is an external version configured for this, it will return null
		//                  from here, because that external version will be loaded async
		//				    Additionally if it is a "feature", then also it returns null because no separate
		//                  object is created for a feature
		//                  It will also be null, if a customized extension is hapenning for a plugin
		this.extend = function(type, name, alias, id, extender) {
			// NOTE: This function knows about variety of plugin types, even if these are not
			// registered at the moment. 
			
			// case of only 2 and 3 arguments
			if (arguments.length === 2 && isString(type) && isFunction(name)) {
				// passed only plugin name and extender
				extender = name;
				name = type;
				type = "custom";
				alias = "";
				id = name;
			} else if (type !== "view" && type !== "page" && arguments.length === 3 && 
						isString(type) && isString(name) && isFunction(alias)) {
				// passed only plugin name, id and extender
				extender = alias;
				id = name;
				name = type;
				type = "custom";
				alias = "";
			};
		
			// control types
			// only types those are registred and a special type - feature
			// are allowed. 'root' though is a special type (framework root itself) is not
			// to be processed here - that's why excluded
			var possibleTypes = "'feature', ";
			var rootName = $f.p.plugins.types.root;
			$.each($f.p.plugins.types, function(name, value) {
				// ignore root
				if (name !== rootName) {
					possibleTypes+= "'" + value + "', ";
				};
			});
			var target = "";
			var plugin = null;
			var isFeature = false;
			var isCustomizedExtensionOfAPlugin = false;
			var isCustomizedExtensionError = true;
			var pluginToExtend = null;
			if (isEmpty(type)) {
				type = "custom";
			};
			if (possibleTypes.indexOf("'" + type + "'") === -1) {
				try {
					pluginToExtend = eval("$f." + type);
					isCustomizedExtensionOfAPlugin = true;
					if (pluginToExtend && pluginToExtend.handle && isFunction(pluginToExtend[name])) {
						// go ahead
						isCustomizedExtensionError = false;
					} else {
						$f.error("Specified object is not a plugin or does not contain specified method to extend. '" + type + "'. Cannot extend.", false, false);
					};
				} catch (ex) {
					pluginToExtend = null;
					$f.error("Failed to reach to specified plugin or its method to extend. '" + type + "'. Cannot extend.", false, false);
				};
			};
			
			if (isCustomizedExtensionOfAPlugin) {
				// call specified method if available
				if (!isCustomizedExtensionError) {
					var args = [];
					$.each(arguments, function(i, arg) {
						// skip first 2 arguments (which are type and name)
						if (i > 1) {
							args.push(arg);
						};
					});
					pluginToExtend[name].apply(pluginToExtend, args);
				};
			} else {
				// special parameters handling for special types
				// app: type=type, name=id, alias=extender
				// page: type=type, name=id, alias=extender
				// master: type=type, name=id, alias=extender
				// view: type=type, name=id, alias=extender
				// module: type=type, name=name, alias=id, id=extender
				// pane: type=type, name=name, alias=id, id=extender
				// system: type=type, name=name, alias=alias, id=id, extender=extender
				// feature: type=type, name=name, target=alias, id=id, extender=extender
				// custom: type=type, name=name, alias=alias, id=id, extender=extender
				
				// name - type combination restrictions
				if (type === "app") {
					id = name;
					name = "app";
					extender = alias;
					alias = "";
				};
				if (type === "page" && name !== "page_default") {
					id = name;
					name = "page";
					extender = alias;
					alias = "";
				};
				if (type === "master" && name !== "master_default") {
					id = name;
					name = "master";
					extender = alias;
					alias = "";				
				};
				if (type === "view") {
					id = name;
					name = "view_" + id.replace(/-/g, "_"); // view is given a name automatically using its id ("view" cannot be given because only active view gets "view" reference)
					extender = alias;
					alias = "";				
				};
				if (type === "module") {
					extender = id;
					id = alias;
					alias = "";			
				};	
				if (type === "pane") {
					extender = id;
					id = alias;
					alias = "";			
				};						
				if (name === "app" && type !== "app") {
					type = "app";
				};
				if ((name === "page" || name === "page_default") && type !== "page") {
					type = "page";
				};
				if ((name === "master" || name === "master_default") && type !== "master") {
					type = "master";
				};	
				if ((name === "view_" + id.replace(/-/g, "_")) && type !== "view") {
					type = "view";
				};				
				if (type === "feature") {
					target = alias;
					if (alias.indexOf(",") !== -1)
					{
						if (alias.indexOf("*") !== -1) {
							target = "*"; // since one of the multiple targets is *, it essentially means *
						} else {
							target = alias.split(","); // multiple targets array
						};
					}
					alias = "";
					isFeature = true;
				};
				
				// extract namespace (only if custom, module or pane types)
				var namespace = "";
				if (type === "custom" || type === "module" || type === "pane") {
					var idx = name.lastIndexOf(".");
					if (idx === -1) {
						namespace = "";
					} else {
						namespace = name.substring(0, idx);
						name = name.substring(idx + 1);
					};
				};

				// check on fixed names
				var isFixedName = (fixedPluginNames.indexOf("'" + name + "'") !== -1);

				// one more case
				if (type === "system" && !isFixedName) {
					type = "custom";
				};
				
				// process only if everything is correct
				if (isEmpty(name) || isEmpty(id) || !extender || (isFeature && !target)) {
					$f.error("Incomplete definition for '" + name + "'. Cannot extend.", false, false);
				} else {
					// load feature or plugin
					if (isFeature) {
						// load feature
						addFeature(name, target, id, extender);					
					} else {
						var isLoadInternalVersion = false;
						if ($f.has.feature("dynamicExtend")) {
							// external version check is done only for 'app' and 'system' types
							// when dynamicExtend feature is available
							// not required for any other types
							// external version check (skip checking if this check was already done in 
							// internal version load cycle and a flag was set for this
							var isSkipLoading = false;
							var isLoadExternalVersion = false;
							var externalVersionConfig = "";
							var externalPluginType = "";
							if (type === "module") {
								externalPluginType = "module";
							} else if (type === "pane") {
								externalPluginType = "pane";
							};
							if (type === "app" || type === "system") {
								if (!$f.vars.lookingForExternalVersionOf[name]) {
									// check for external version
									if ($f.config.options.namedPlugins[name]) {
										externalVersionConfig = $f.config.options.namedPlugins[name];
										if (externalVersionConfig.toLowerCase() === "off") {
											isSkipLoading = true;
										} else if (!isEmpty(externalVersionConfig)) {
											isLoadExternalVersion = true;
										};
									};		
										
									// set flag, so it is not checked again when loading external version
									if (isLoadExternalVersion) {
										$f.vars.lookingForExternalVersionOf[name] = true;
									};
								} else {
									// don't check for external version
									// instead remove flag now
									delete $f.vars.lookingForExternalVersionOf[name];
								};
							};
						
							// skip, load external version or load defined
							if (!isSkipLoading) {
								if (isLoadExternalVersion) {
									// load external version
									$f.extend.fromFile(externalVersionConfig, name, externalPluginType, null);
								} else {
									isLoadInternalVersion = true;
								};
							};
						} else {
							isLoadInternalVersion = true;
						};
						
						// load internal version if required
						if (isLoadInternalVersion) {
							plugin = addPlugin(type, namespace, name, isFixedName, alias, id, extender);
						};
					};
				};
			};
			
			// return plugin
			return plugin;
		};
		
		// forwards to extend
		this.extend.system = function(name, alias, id, extender) {
			// arguments fix
			if (arguments.length === 3 && isString(name) && isString(alias) && isFunction(id)) {
				extender = id;
				id = alias;
				alias = "";
			};			
		
			// forward
			return $f.extend("system", name, alias, id, extender);
		};
		
		// forwards to extend
		this.extend.custom = function(name, alias, id, extender) {
			// arguments fix
			if (arguments.length === 2 && isString(name) && isFunction(alias)) {
				extender = alias;
				id = name;
				alias = "";
			} else if (arguments.length === 3 && isString(name) && isString(alias) && isFunction(id)) {
				extender = id;
				id = alias;
				alias = "";
			};
			
			// forward
			return $f.extend("custom", name, alias, id, extender);
		};
		
		// forwards to extend
		this.extend.feature = function(name, targets, id, extender) {
			// forward
			return $f.extend("feature", name, targets, id, extender);
		};
		
		// write trace log entry if tracing is on
		// params:
		//	message (string): trace log entry that is to be written
		// returns (void):
		this.trace = function(message) {
			if ($f.config.options.isTrace) {
				// add to trace log
				$f.vars.traceLog.push({pointInTime: new Date().getTime().toString(), log: message});
				
				// write to console immediately if required
				if (window.console && $f.config.options.isWriteToConsole) {
					if (isFunction(console.info)) {
						console.info(message);
					};
				};
			};
		};
		
		// reset application
		// maintains: nothing, clears: session, states, cache, history and then go home
		// returns (void):
		this.reset = function() {
			// let plugins do what they want
			$.each($f.all.plugins("d"), function(i, plugin) {
				// forward to features
				plugin.forwardToFeatures("onReset");
				
				// call onReset
				plugin.onReset();
			});
			
			// set flag
			if ($f.state) {
				$f.state.isAppRestarting = true;
			};
			
			// go home
			if ($f.nav) {
				$f.nav.goHome();
			};	
		};
		
		// restart application
		// maintains: session, states, clears: history and then go home
		// returns (void):
		this.restart = function() {
			// let plugins do what they want
			$.each($f.all.plugins("d"), function(i, plugin) {
				// forward to features
				plugin.forwardToFeatures("onRestart");
				
				// call onRestart
				plugin.onRestart();
			});

			// set flag
			if ($f.state) {
				$f.state.isAppRestarting = true;
			};
			
			// go home
			if ($f.nav) {
				$f.nav.goHome();
			};
		};
	
		// error manager
		// params:
		//	errorMessage (string): error message
		// 	isShow (boolean): if error message is to be shown in an alert
		// 	isThrow (boolean): if an error is to be thrown
		// 	ex (object): Optional. Exception object, if available
		// returns (void):
		this.error = function(errorMessage, isShow, isThrow, ex) {
			// jQuery error scenario
			if (isObject(errorMessage)) {
				errorMessage = "Unknown error."
			};
			
			// add exception to error message, if defined
			if (ex) {
				errorMessage = errorMessage + " Error: '" + ex.toString() + "'.";
			};
			
			// log if logger plugin is hooked
			if ($f.logger) {
				$f.logger.log(errorMessage);
			};
			
			// show if required
			if ((isShow || ($f.config.options.isDebug && $f.config.options.isShowAllErrorsInDebugMode)) && !$f.vars.isSupressShowingErrorOnce) {
				$f.alert(errorMessage);
			};
			
			// reset after skipping showing error once
			$f.vars.isSupressShowingErrorOnce = false;

			// write to console immediately if required and in debug mode
			if ($f.config.options.isDebug && window.console && $f.config.options.isWriteToConsole) {
				if ((!isShow && !isThrow) && isFunction(console.warn)) {
					console.warn(errorMessage);
				} else if (isFunction(console.error)) {
					console.error(errorMessage);
				};
				if (ex && isFunction(console.dir)) {
					console.dir(ex);
				};
			};
			
			// send to trace as well
			if ($f.config.options.isTrace) {
				$f.trace("Error: " + errorMessage);
			};
			
			// throw if required and is not supressed
			if (isThrow && !$f.config.options.isSupressThrowErrors) {
				// check if application error handler is not set
				// this means, it will break from this place itself
				// so do required screen cleanup with proper information
				if (!$f.app && !isFunction($f.app.onApplicationError)) {
					// clear body
					var body = $("body");
					body.empty();
					
					// blue screen of death
					body.css({backgroundColor: 'blue'});
					body.css({color: 'white'});
					
					// current error
					body.html("<br /><b>*** unhandled exception: " + errorMessage + " ***</b><br /><br />");
					
					// show trace if any
					var item = null;
					body.append("<br />TRACE:<br />");
					for(var i = $f.vars.traceLog.length - 1; i < 0; i--) {
						item = $f.vars.traceLog[i];
						body.append(item.pointInTime + ": " + item.log + "<br />");
					};
				};
				
				// throw exception
				throw new Error(errorMessage);
			};
		};
	
		// controlled alerts
		// params:
		//	message: message to show in alert
		// returns (void):
		this.alert = function(message) {
			// show alert message if alerts are not supressed or in debug mode
			if (!$f.config.options.isSupressAlerts || $f.config.options.isDebug) {
				// modity message to show that this message is only because of debug mode
				if ($f.config.options.isSupressAlerts && $f.config.options.isDebug && message.indexOf("DEBUG: ") === -1) {
					message = "DEBUG: " + message;
				};
				
				// show
				alert(message);
			};
		};
		
		// debug only alerts 
		// params:
		//	message: message to show in alert
		// returns (void):		
		this.alert.debug = function(message) {
			// show only in debug mode
			if ($f.config.options.isDebug) {
				$f.alert("DEBUG: " + message);
				
				// write to console immediately if required
				if (window.console && $f.config.options.isWriteToConsole) {
					if (isFunction(console.warn)) {
						console.warn(message);
					};
				};
			};
		};
		
		// confirmation alert
		// params:
		//	message: confirmation message to show in alert
		// returns (boolean):
		// 	true: if OK
		// 	false: if Cancel or Escape or Close
		this.confirm = function(message) {
			// return
			return confirm(message);
		};
		
		// input prompt
		// params:
		//	message: confirmation message to show in alert
		// returns (string): entered value in prompt box or null if cancel
		this.prompt = function(message, defaultValue) {
			// return
			return prompt(message, defaultValue);
		};
		
		// show custom (prompt) dialog 
		// params:
		//	url (string): url that would be opened in dialog
		//	args (string): arguments to be passed to dialog
		//	options (object): any options to control dialog window
		// returns (object): returns returned object from dialog
		this.prompt.dialog = function(url, args, options) {
			// process url to get resolved/complete path
			return window.showModalDialog(url, args, options);
		};
		
		// frees up reference of $f to what it originally found
		// returns (object): current fluid object
		this.noConflict = function() {
			// reset $f reference to old
			delete window["$f"];
			if (isDefined(old_f_reference)) {
				window.$f = old_f_reference;
			};
			
			// note: fluid object will still be available
			
			// return current object
			return this;
		};
		
		// reinstate $f to fluid instance
		// returns (void):
		this.reinstate = function() {
			window.$f = this;
		};
		
		// private functions 
		// not for public use
		// backward compatibility is not guranteed
		this.p = {
			// get plugins queue for which files are not included so far
			getPendingIncludeFilesQueue: function() {
				// return
				return $f.vars.pendingIncludeFilesQueue;
			},
			
			// get features queue for which files are not included so far
			getPendingFeatureIncludeFilesQueue: function() {
				// return
				return $f.vars.pendingFeatureIncludeFilesQueue;
			},
			
			// reqd query string values
			getQueryStrings: function()
			{
				// read
				var vars = [], hash;
				var mainUrl = window.location.href.split('#')[0];
				if (mainUrl.indexOf('?') !== -1) {
					var hashes = mainUrl.slice(window.location.href.indexOf('?') + 1).split('&');
					for(var i = 0; i < hashes.length; i++)
					{
						hash = hashes[i].split('=');
						vars.push(hash[0]);
						vars[hash[0]] = hash[1];
					}
				};
				
				// return
				return vars;
			},
			
			// plugin functionality
			plugins: {
				// finds the already loaded plugin and returns its instance
				// params:
				//	name (string): name of the plugin to look for
				//	               if plugin has namespace in it, it should be part of this string
				//  type (string): type of plugin
				//				   "pane", "module", "plugin", "" (empty means "plugin")
				// return (object): returns plugin object if success, null otherwise	
				get: function(name, type) {
					// forward
					return getPlugin(name, isModule, isPane);
				},
				
				// plugin types
				types: {
					root: "root", 
					system: "system",
					custom: "custom"
				},
				
				// feature targets
				// returns (array): returns an array of plugin objects of a particular type on which a feature 
				//                  is to be added when requested
				featureTargets: {
					root: function() {
						// create list
						var plugins = [];
						plugins.push($f);
						
						// return
						return plugins;
					},
					system: function() {
						// return
						return $f.all.plugins.system();
					},
					custom: function() {
						// return
						return $f.all.plugins.custom();
					}
				},
				
				// plugin classes
				// convention here is that except pluginBase, which is base of all plugins,
				// for every other type of plugin, the name should be "<typeName>PluginBase"
				// where <typeName> is the string defined for type in plugins.types above
				classes: {
					// base definition of all fluid plugins
					pluginBase: function() {
						// self reference to be used inside structured functions
						var self = this;
						
						// plugin handle
						this.handle = {
							// unique id of the plugin
							id: "", 
							
							// unique name of the plugin in given namespace
							name: "",
							
							// name of the file from which this plugin was loaded
							file: "",
							
							// unique namespace in context of $f or $f.modules or $f.panes, as the case may be 
							namespace: "",
							
							// fully qualified name 
							qualifiedName: "",
						
							// type of the plugin
							type: "",
							
							// list of plugin ids which have configured this plugin
							configuredBy: "",
							
							// if plugin
							isPlugin: true,
							
							// if this is an object (controlled by $f.objects)
							isObject: false,
							
							// if system plugin
							isSystemPlugin: false,
							
							// if app plugin
							isAppPlugin: false,				
							
							// basic types checks
							isModule: function() {
								return (self.handle.type === $f.p.plugins.types.module);
							},
							isPane: function() {
								return (self.handle.type === $f.p.plugins.types.pane);
							},				
							isPage: function() {
								return (self.handle.type === $f.p.plugins.types.page);
							},
							isView: function() {
								return (self.handle.type === $f.p.plugins.types.view);
							},
							isMaster: function() {
								return (self.handle.type === $f.p.plugins.types.master);
							},
							isCustom: function() {
								return (self.handle.type === $f.p.plugins.types.custom);
							},
							isApp: function() {
								return (self.handle.type === $f.p.plugins.types.app);
							},
							isSystem: function() {
								return (self.handle.type === $f.p.plugins.types.system);
							},
							isRoot: function() {
								return (self.handle.type === $f.p.plugins.types.root);
							},			

							// flag that is set to true when plugin include files are completely processed
							isIncludeProcessed: false,
							
							// flag that is set to true when plugin's resources which are loaded async are processed
							isResourcesProcessed: false,			
							
							// flag that is set to true when plugin onInit is called and it was successful
							isInit: false,
							
							// flag that is set to true when plugin onLoad is called
							isLoad: false,

							// flag that is set to true when plugin onReady is called
							isReady: false,
							
							// called when plugin include files are processed
							onIncludeComplete: function() {
								if (!self.handle.isIncludeProcessed) {
									// let plugin initialize itself (if not already done)
									// environment is the only plugin that will be initialized even before this method 
									// is called, rest all will route through here only
									if (!self.handle.isInit) {
										// call on init
										self.handle.isInit = self.onInit();
										if (!self.handle.isInit) {
											$f.error("'" + name + "' plugin failed to initialize.", false, false);
										} else {
											// forward to features
											self.forwardToFeatures("onInit");
										};						
									};
									
									// set flag (irrespective of above condition)
									self.handle.isIncludeProcessed = true;
									
									// configure and load plugin if not already called and app level load call process (if isAllBatchLoaded = true) is already executed 
									if ($f.state.isAllBatchLoaded && !self.handle.isLoad) {
										// get it configured from all other plugins which can configure plugins
										// and let it configure other plugins, if required
										configurePlugin(self, true, false); // pass true, so that all processings which is done on load in batch is done for this plugin also
									
										// call on load as well (since onLoad for every other plugin is already called)
										self.onLoad();

										// forward to features
										self.forwardToFeatures("onLoad");
										
										// set flag
										self.handle.isLoad = true;
										
										// add trace message
										$f.trace("Plugin '" + self.handle.name + "' is loaded. Init: " + self.handle.isInit.toString() + ", Load: " + self.handle.isLoad.toString() + ", Ready: " + self.handle.isReady.toString() + ".");
									};
									
									// call ready of the plugin if not already called and app level ready call process (if isAllBatchReady = true) is already executed 
									if ($f.state.isAllBatchReady && !self.handle.isReady) {
										// call on ready as well (since onReady for every other plugin is already called)
										self.onReady();

										// forward to features
										self.forwardToFeatures("onReady");

										// set flag
										self.handle.isReady = true;
										
										// add trace message
										$f.trace("Plugin '" + self.handle.name + "' is ready. Init: " + self.handle.isInit.toString() + ", Load: " + self.handle.isLoad.toString() + ", Ready: " + self.handle.isReady.toString() + ".");
									};
									
									// add trace message
									$f.trace("Plugin '" + self.handle.name + "' is initialized. Init: " + self.handle.isInit.toString() + ", Load: " + self.handle.isLoad.toString() + ", Ready: " + self.handle.isReady.toString() + ".");
									
									// inform app about this plugin (except for app plugin itself)
									if ($f.app && isFunction($f.app.onAfterPluginLoad) && !self.handle.isApp()) {
										$f.app.onAfterPluginLoad(self);
									};
								};
							},
							
							// features that are added to this plugin
							features: {},
							
							// extension options that are to be used for extension 
							extensionOptions: {
								// all these members will be ignored while copying at level 0
								ignore: "'host', 'forwardToFeatures', ",
								
								// all same name members here under will go for partial copy process and 
								// members defined in each list will be ignored while copying at level 1 for each member respectively 
								partialCopy: {
									handle: "'id', 'name', 'file', 'namespace', 'qualifiedName', 'type', 'configuredBy', 'isIncludeProcessed', 'isResourcesProcessed', 'isInit', 'isLoad', 'isReady', 'onIncludeComplete', 'features', 'extensionOptions', 'isExtensionDone', 'onExtensionComplete', ",
									info: "",
									config: ""
								}
							},
							
							// is extension done
							isExtensionDone: false,
							
							// called when all extensions are done
							onExtensionComplete: function() {
								// process only if not already processed
								if (!self.handle.isExtensionDone) {
									// set
									self.handle.isExtensionDone = true;
									
									// move "has" and "all" functions around for logical and easy to use syntax
									// this is required to because some plugins might have their own has and
									// all structures or functions
									if (!self.has) {
										// add as structure
										self["has"] = {};
									};
									// add function to strcuture
									self.has["feature"] = self.has_Feature; delete self["has_Feature"];
									
									if (!self.all) {
										// add as structure
										self["all"] = {};
									};
									// add function to strcuture
									self.all["features"] = self.all_Features; delete self["all_Features"];
								};
							}
						};

						// framework root object reference
						this.host = null;
						
						// plugin info
						this.info = {
							// title of the plugin
							title: "",
							
							// version of the plugin (major.minor.build)
							version: "",
							
							// author of the plugin
							author: "",
							
							// copyright notice
							copyright: "",
							
							// detailed description of the plugin
							description: "",
							
							// web url of the plugin if any
							web: "",
							
							// license of the plugin, if any
							license: {
								text: "",
								url: ""
							}
						};
						
						// pre-initialization handler
						// returns (boolean): 
						//	true: if success 
						//	false: if failed
						this.onPreInit = function(plugin) { return true; };
						
						// initialization handler
						// returns (boolean): 
						//	true: if success 
						//	false: if failed
						this.onInit = function(plugin) { return true; };
						
						// load handler
						// returns: (void)
						this.onLoad = function() { };
						
						// ready handler
						// returns: (void)
						this.onReady = function() { };
						
						// unload handler
						// returns: (void)
						this.onUnload = function() { };		
						
						// reset handler
						// returns: (void)
						this.onReset = function() { };
						
						// restart handler
						// returns: (void)
						this.onRestart = function() { };
						
						// configure given plugin 
						// this is called for each plugin if canConfigurePlugins is set to true
						// params:
						//	plugin (object): plugin object to configure
						//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
						//                                        this plugin otherwise should also be done now with
						//                                        this plugin, because this is being loaded after all
						//                                        batch processing is done at load time
						//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
						// 										    a new feature is added to plugin which may have added
						//											some members those required reconfiguration			
						// returns (void):	
						this.configure = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {	
						};

						// check if specified feature is available in the plugin
						// params: 
						//	name (string): name of the feature to check
						// returns (boolean): true, if available, false otherwise
						this.has_Feature = function(name) {
							// return
							return hasFeature(name, self);
						};
						
						// gets an array of all loaded features in this plugin
						// returns (array): features list
						this.all_Features = function() {
							// return
							return getFeaturesList(self);
						};
						
						// forward a call to all features which support forward handling
						// params: 
						//	forwardName (string): forward name
						//  args (object literal): forward arguments
						// returns (void):
						this.forwardToFeatures = function(forwardName, args) {
							// forward 
							forwardCallToFeatures(self, forwardName, args);
						};
						
						// plugin configuration
						this.config = {
							// zIndex of the plugin controls the sequence of calling
							// onLoad, onReady and onUnload handlers of the plugins
							// with respect to each other
							// valid values are between 0 to 99999. Values between 0 to 9999
							// and 90001 upwards are reserved for framework plugins. 
							// For custom plugins use any value between 10000 to 90000.
							zIndex: 10000,
							
							// can this plugin configure other plugins
							// if this is set to true, after plugins are initialized, these will be
							// given to this plugin's configure method to do required configuration
							canConfigurePlugins: false
						};
					},
					
					// extended definition for all custom plugins - over base definition
					// anything that is defined here would be shared in all
					// plugins that are extended from this base
					customPluginBase: function (self) {
					},
					
					// extended definition for all system plugins - over base definition
					// anything that is defined here would be shared in all
					// plugins that are extended from this base
					systemPluginBase: function (self) {
						// plugin handle
						this.handle = {
							// if system plugin
							isSystemPlugin: true
						};
					}
				}
			}
		};
	};
	
	// root instance and initialization
	var old_f_reference = window.$f;
	window.fluid = new _fluid();
	window.$f = window.fluid;
	$f.onPreInit();
	$f.onInit(); 
	if ($f.info.version.package.isKernel()) {
		// since no system plugin is loaded in kernel, this must be called from here itself
		$f.handle.onIncludeComplete(); 
	};
}(window));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: environment
  *  Dependencies: 	
  *		- $f
  *  Functionality:
  *		- this plugin provides environmental status, information and operations.
  *		- it also call offline cache related event handlers on app plugin.
  *
  */
(function($f) { $f.extend.system("environment", "env", "41611e3d-9fa7-42ac-8cb2-6548d1024533", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// identify and set startup html
	var setStartupHtml = function() {
		var startupHtml = "";
		if ($f.deploymentMode.isPortable()) {
			startupHtml = self.p.urlToLocalPath(window.document.location.href);
		} else if ($f.deploymentMode.isWrapped()) {
			// TODO: Handle wrappedApp case
		} else {
			// any other web served mode
			if (self.has.feature("web")) {
				root = self.web.p.getStartupHtml();
			};
		};	
		
		// set
		self.vars.startupHtml = startupHtml;
	};
	
	// identify and set root folder
	var setRoot = function() {
		var startupHtml = self.vars.startupHtml;
		var root = "";
		if ($f.deploymentMode.isPortable()) {
			var ch = startupHtml.charAt(startupHtml.indexOf(":") + 1); // read / or \ after drive:
			var pos = startupHtml.lastIndexOf(ch);
			root = startupHtml.substring(0, pos);				
		} else if ($f.deploymentMode.isWrapped()) {
			// TODO: Handle wrappedApp case
		} else {
			// any other web served mode
			if (self.has.feature("web")) {
				root = self.web.p.getRoot();
			};
		};		
		
		// set
		self.vars.currentRoot = root;
	};
	
	// identify and set data root folder
	var setDataRoot = function() {
		var dataRoot = "";
		if ($f.deploymentMode.isPortable()) {
			// local running mode
			dataRoot = $f.config.options.dataFolder;
			if (isEmpty(dataRoot)) {
				dataRoot = "data"; // inbuilt default
			};
		} else if ($f.deploymentMode.isWrapped()) {
			// TODO: Handle wrappedApp case
		} else if ($f.config.options.isEnableLocalFileSystemAccess) {
			// any other web served mode
			if (self.has.feature("web")) {
				dataRoot = self.web.p.getDataRoot();
			};
		};
		
		// set
		self.vars.currentDataRoot = dataRoot; // it will be empty if non-portable version and file system access is disabled OR environment's web feature is not added
	};
		
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "Environment",
		description: "Provides environmental status, information and operations."
	};
		
	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// identify browser
		var userAgent = window.navigator.userAgent.toLowerCase();
		self.browser.userAgent = userAgent;
		self.browser.version = (userAgent.match(/.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/) || [])[1];
		self.browser.isChrome = /chrome/.test(userAgent);
		self.browser.isSafari = /webkit/.test(userAgent) && !/chrome/.test(userAgent);
		self.browser.isOpera = /opera/.test(userAgent);
		self.browser.isIE = /msie/.test(userAgent) && !/opera/.test(userAgent);
		self.browser.isMozilla = /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent);

		self.browser.isTouchDevice = !!('ontouchstart' in window);
		
		// if mobile browser
		// picked from: http://detectmobilebrowsers.com/
		if (/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|meego.+mobile|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(userAgent)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0,4))) {
			self.browser.isMobile = true;
			self.browser.isAndroid = /Android/.test(userAgent);
			self.browser.isGalaxyTab = /GT-P1000|GT-P1000R|GT-P1000M|SGH-T849|SHW-M180S|GT-I9000T/.test(userAgent);
			self.browser.isWindowsTab = /Tablet PC 1.7|Tablet PC 2.0/.test(userAgent);
			self.browser.isiPhone = /iPhone/.test(userAgent);
			self.browser.isiPad = /iPad/.test(userAgent);
			self.browser.isiPod = /iPod/.test(userAgent);
			self.browser.isiDevice = /(iPhone|iPod|iPad)/.test(userAgent);
			self.browser.isTablet = (self.browser.isiPad || self.browser.isGalaxyTab || self.browser.isWindowsTab);
			self.browser.isiOS = self.browser.isiDevice;
			self.browser.isBlackBerry = /BlackBerry/.test(userAgent);
			self.browser.isWindowsPhone = /Windows Phone/.test(userAgent);
			self.browser.isWebOS = /webOS/.test(userAgent);
			self.browser.isZuneWP7 = /ZuneWP7/.test(userAgent);
		} else {
			self.browser.isDesktop = true;
		};
		
		// identify startup html
		setStartupHtml();
		
		// identify current root
		setRoot();
		
		// identify current data root folder
		setDataRoot();
		
		// check java presence and initiate Java load, if required
		self.loadJavaIfRequired();

		// return
		return true; 
	};
		
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// holds current root folder
		currentRoot: "",
		
		// holds current data root folder
		currentDataRoot: "",
		
		// holds startup html file name
		startupHtml: "",		
	};
		
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 50				
	};
	
	// startup html file
	// returns (string): name of the startup html file
	this.startupHtml = function() {
		// return
		return self.vars.startupHtml;
	};

	// get root folder path
	// returns (string): returns file system path of root folder where startup html is placed
	this.root = function() {
		// return 
		return self.vars.currentRoot;
	};

	// get data root folder path
	// returns (string): returns file system path of root folder where data files are placed
	this.dataRoot = function() {
		// return 
		return self.vars.currentDataRoot;
	};
	
	// inform and initiate loading java, if required
	// returns (void):
	this.loadJavaIfRequired = function() {
		// update plugins information
		self.browser.plugins.hasJava = navigator.javaEnabled();
		
		// try and install if not installed but required or mandatory
		if (!self.browser.plugins.hasJava) {
			// check if required
			var isRequired = false;
			if ($f.deploymentMode.isPortable()) {
				isRequired = true;
			} else if ($f.deploymentMode.isWrapped()) {
				// TODO: Handle wrappedApp case
			} else {
				// any other version and local file system access is enabled
				if ($f.config.options.isEnableLocalFileSystemAccess) {
					isRequired = true;
				};
			};
		
			// initiate load
			var message = "";
			if (isRequired) {
				message = "This app requires Java runtime engine (JRE) Version " + $f.config.options.minJavaVersion + " to execute. Do you want to install it now?";
				
				// ask use
				if ($f.confirm(message)) {
					// initiate load in same browser
					window.navigate($f.config.options.javaInstallerUrl, "_self");
					
					// stop now
					throw "Install JRE and then restart.";
				} else {
					var message = "To function properly, this app requires Java Runtime Engine (JRE) Version " + $f.config.options.minJavaVersion;
					if ($f.infoBar) {
						$f.infoBar(message, "warning");
					} else {
						$f.alert(message);
					};
				};
			};
		};
	};
	
	// gets current device orientation 
	// returns (number):
	//	0 - portrait
	//	1 - landscape
	this.orientation = function() {
		var orientation = 1; // default for drsktop
		if (!self.browser.isDesktop) {
			if(window.innerHeight > window.innerWidth) {
				orientation = 0; // portrait
			} else {
				orientation = 1; // landscape
			};
		} else {
			if ($f.emulator && $f.emulator.isEmulating.get()) {
				orientation = $f.emulator.emulatedOrientation();
			};
		};
		
		// return
		return orientation;
	};

	// current browser information
	this.browser = { 
		// browser plugins information
		plugins: {
			// various flags
			hasJava: false
		},
	
		// opens browser's print dialog
		// returns (void):
		print: function() {
			window.print();
		},		
	
		// user agent
		userAgent: "",
		
		// browser version
		version: "",

		// various flags
		isMobile: false,
		isDesktop: false,
		isTablet: false,
		
		isTouchDevice: false,
		
		isGalaxyTab: false,
		isWindowsTab: false,
		isiPad: false,
		
		isAndroid: false,
		isWindowsPhone: false,
		isWebOS: false,
		isiOS: false,

		isiPhone: false,
		isiPod: false,
		isBlackBerry: false,
		isZuneWP7: false,

		isiDevice: false,

		isChrome: false,
		isSafari: false,
		isOpera: false,
		isIE: false,
		isMozilla: false
	};	

	// startup html known containers
	this.container = {
		// parent container of...
		parentOf: {
		},
		
		// container in startup layout where all UI elements are placed
		// returns (string): DOM element id (configured or default)
		root: function() {
			// return
			return "root"; // inbuilt default				
		},
		
		// container in startup layout where all unstructure UI elements are finally moved
		// returns (string): DOM element id (configured or default)
		unstructuredBody: function() {
			// return
			return "unstructuredBody"; // inbuilt default				
		},

		// container in startup layout where all unstructure UI elements are placed
		// returns (string): DOM element id (configured or default)
		body: function() {
			// return
			return "body"; // inbuilt default				
		},
		
		// container in startup layout where all loading UI elements are placed
		// returns (string): DOM element id (configured or default)
		loading: function() {
			var containerElementId = $f.config.options.loadingElementId;
			if (isEmpty(containerElementId)) {
				containerElementId = "loadingBar"; // inbuilt default
			};

			// return
			return containerElementId;			
		},
		
		// container in startup layout where all templates are loaded
		// returns (string): DOM element id (configured or default)
		templates: function() {
			// return
			return "templates"; // inbuilt default				
		}
	};

	// private functions 
	// not for public use
	// backward compatibility is not guranteed
	this.p = {
		// converts url to local path
		urlToLocalPath: function(url) {
			// remove any location or query part of the url
			var originalPath = url.split("#")[0].split("?")[0];
			
			// convert file://localhost/ to file:///
			if (originalPath.indexOf("file://localhost/") === 0) {
				originalPath = "file://" + originalPath.substr(16);
			};
			
			// convert to a native file format
			// "file:///x:/path/path/path..." - pc local file --> "x:\path\path\path..."
			// "file://///server/share/path/path/path..." - FireFox pc network file --> "\\server\share\path\path\path..."
			// "file:///path/path/path..." - mac/unix local file --> "/path/path/path..."
			// "file://server/share/path/path/path..." - pc network file --> "\\server\share\path\path\path..."
			var localPath = "";
			if (originalPath.charAt(9) === ":") { // PC local file
				localPath = unescape(originalPath.substr(8)).replace(new RegExp("/","g"),"\\");
			} else if (originalPath.indexOf("file://///") === 0) { // Firefox PC network file
				localPath = "\\\\" + unescape(originalPath.substr(10)).replace(new RegExp("/","g"),"\\");
			} else if (originalPath.indexOf("file:///") === 0) { // Mac/UNIX local file
				localPath = unescape(originalPath.substr(7));
			} else if (originalPath.indexOf("file:/") === 0) { // Mac/UNIX local file
				localPath = unescape(originalPath.substr(5));
			} else if (originalPath.indexOf("//") === 0) { // PC network file
				localPath = "\\\\" + unescape(originalPath.substr(7)).replace(new RegExp("/","g"),"\\");
			} else {
				localPath = originalPath;
			};
			
			// convert all "/" to "\"
			localPath  = localPath.replace(/\//g, "\\");				
			
			// return
			return localPath;	
		}	
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: utils
  *  Dependencies: 
  * 	- $f
  *  Functionality:
  *		- this plugin provides general purpose utility functions.
  *		- it does not process any other plugins.
  *
  */
(function($f) { $f.extend.system("utils", "5945b26a-2200-47d1-8194-daa81cbd05aa", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = { 
		title: "Utilities",
		description: "Provides general purpose utility functions."
	};

	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 25
	};
	
	// string operations
	this.string = {
		// convert to boolean from string
		// params:
		// 	string (string): text to be converted to boolean
		// returns (boolean): 
		toBool: function(string) {
			switch(string.toLowerCase()) {
				case "true": 
				case "yes": 
				case "1": 
					return true;
				
				case "false": 
				case "no": 
				case "0": 
				case null: 
				case "": 
					return false;
				
				default: 
					return Boolean(string);
			};
		},	
		
		// convert to date from string
		// params:
		// 	string (string): text to be converted to date
		// returns (date): 
		toDate: function(string) {
			return new Date(string);
		},	

		// cound the number of occurance of a string in another
		// params:
		//	searchIn (string): search in which string
		//	searchWhat (string): search what string
		//                       is there are special characters - they have to be double escaped each
		//                       e.g., if looking for a * pass \\* instead. All basic regex string formation
		//                       rules apply
		// returns (number): number of times searchWhat appeared in searchIn
		occurance: function(searchIn, searchWhat) {
			// search via regular expression formation
			return (searchIn.match(new RegExp(searchWhat, 'g'))||[]).length;		
		},
		
		// check if given string exists in another string
		// params:
		//	string (string): which string to check in
		//	contains (string): which string to look for
		// returns (boolean): true/false
		exists: function(string, contains) {
			// return
			return (string.indexOf(contains) !== -1);
		},
		
		// check if given string starts with specified string
		// params:
		//	string (string): which string to check in
		//	startsWith (string): which string to look for
		// returns (boolean): true/false
		startsWith: function(string, startsWith) {
			// return
			return (string.indexOf(startsWith) === 0); // 0 is the starting position
		},
		
		// check if given string ends with specified string
		// params:
		//	string (string): which string to check in
		//	endsWith (string): which string to look for
		// returns (boolean): true/false
		endsWith: function(string, endsWith) {
			// return
			var isEndsWith = false;
			if (string.indexOf(endsWith) !== -1) {
				if ((string.indexOf(endsWith) + endsWith.length) === string.length) {
					isEndsWith = true;
				};
			};
			return isEndsWith;
		},		

		// checks if given wildcard string matches with matchedWith string
		// params:
		//	wildCardString (string): string with wild card in it
		//                           Only * wildcard in one of the following ways is supported:
		//							 startsWith: string* OR 
		//							 endsWith: *string OR 
		//							 startsAndEndsWith: stringPart1*stringPart2
		//  matchedWith (string): string which is to be matched with
		// return (boolean): true, if matched, false otherwise
		wildCardMatch: function(wildCardString, matchedWith) {
			// match
			var isMatched = false;
			wildCardString = $.trim(wildCardString);
			if (wildCardString === "*") { 
				// it matches with every string
				isMatched = true;
			} else {
				if (self.string.exists(wildCardString, "*")) {
					if (self.string.startsWith(wildCardString, "*")) {
						// since * is at the beginning, check if matchedWith string ends with given wildcard string without *
						isMatched = self.string.endsWith(matchedWith, wildCardString.substring(1));
					} else if (self.string.endsWith(wildCardString, "*")) {
						// since * is at the end, check if matchedWith string starts with given wildcard string without *
						isMatched = self.string.startsWith(matchedWith, wildCardString.substring(0, wildCardString.length - 1));
					} else {
						// since * is in between, check if matchedWith starts with part1 (before *) and ends with part 2 (after *)
						var parts = wildCardString.split("*");
						isMatched = (self.string.startsWith(matchedWith, parts[0]) && self.string.endsWith(matchedWith, parts[1]));
					};
				} else {
					// since no wild card, so it matches only if they are exactly same
					isMatched = (wildCardString === matchedWith);
				};				
			};

			// return
			return isMatched;
		}
	};

	// object operations
	this.object = {
		// check if specified object has defined structure underneath
		// value of the property being looked for may be null, this just checks for the presence 
		// of property
		// this should be use for deep structures only, for one level its always good to use direct check
		// params:
		//	object (object): which object to check
		//	structure (string): which structure to check
		// returns (boolean): true, if available, false otherwise
		has: function(object, structure) {
			var isFound = false;
			try {
				isFound = isDefined(eval("typeof object." + structure));
			} catch (ex) {
				isFound = false;
			};
			
			// return 
			return isFound;
		},
		
		// returns an array of all functions of given object
		// params:
		//	object (object): object on which to iterate to look for all functions
		// returns (array): string array having names of all methods
		getAllFunctions: function(object) {
			// prepare list
			var functions = [];
			for (var func in object) {
				if (isFunction(object[func])) {
					functions.push(func);
				};
			};
			
			// return
			return functions;
		},	

		// object extender
		// params:
		//  object (object): object that is to be extended
		// 	extenderOptions (extender option object literal): options that control extension
		// 	extender (object literal): object that is to be merged with given object to extend it
		// returns (object): extended object		
		extender: function(object, extenderOptions, extender) {
			// merge-extend members from given extender into given object using extension options
			$.each(extender, function(name, value) {
				// copy only if not in ignore list at level 0
				if (extenderOptions.ignore.indexOf("'" + name + "'") === -1) {
					// perform partial copy if name is in partial copy list at level 0
					if (extenderOptions.partialCopy.hasOwnProperty(name)) {
						// perform partial copy (if defined) or else copy as is
						if (!isDefined(object[name])) {
							// since not defined at this level perform complete copy
							object[name] = value;
						} else {
							$.each(value, function(name2, value2) {
								// copy only if not in ignore list at level 1
								if (extenderOptions.partialCopy[name].indexOf("'" + name2 + "'") === -1) {
									object[name][name2] = value2;
								} else {
									// ignore copying this
								};
							});
						};
					} else {
						// perform complete copy
						object[name] = value;
					};
				} else {
					// ignore copying this
				};
			});
			
			// return
			return object;
		},

		// clone given object
		// params:
		//	object (object): object to clone
		//	customCloneSupportHandler (function): a custom function that will be called to 
		//						                  clone objects which are not primitive or known javascript 
		//										  objects. signature of this function should be:
		//										  object customCloneSupportHandler(copyTo, copyWhatName, copyWhat)
		// returns (object): returns cloned object
		clone: function(object, customCloneSupportHandler) {
			// function to be called recursively for cloning
			var doClone = function(copyTo, copyWhat, copyWhatName, objectCloneHandler) {
				// it target is an array
				var isCopyToAnArray = isArray(copyTo);
				
				// clone function
				if (isFunction(copyWhat)) {
					if (isCopyToAnArray) {
						// if target is an array, push function into it
						copyTo.push(copyWhat);
					} else {
						// copy function in a new property
						copyTo[copyWhatName] = copyWhat;
					};
					
				// clone array
				} else if (isArray(copyWhat)) {
					if (isCopyToAnArray) {
						// clone each item
						var cloneToArray = [];
						$.each(copyWhat, function(i, arrayItemToCopy) {
							cloneToArray = doClone(cloneToArray, arrayItemToCopy, copyWhatName + "[" + i.toString() + "]", objectCloneHandler); 
						});
						
						// push to array
						copyTo.push(cloneToArray);
					} else {
						// create new array
						copyTo[copyWhatName] = [];
						
						// clone each item
						$.each(copyWhat, function(i, arrayItemToCopy) {
							copyTo[copyWhatName] = doClone(copyTo[copyWhatName], arrayItemToCopy, copyWhatName + "[" + i.toString() + "]", objectCloneHandler); 
						});
					};
					
				// clone string object
				} else if (copyWhat instanceof String) { 
					if (isCopyToAnArray) {
						// push new string object
						copyTo.push(new String(copyWhat));
					} else {
						// create new string object
						copyTo[copyWhatName] = new String(copyWhat);
					};
					
				// clone number object
				} else if (copyWhat instanceof Number) { 
					if (isCopyToAnArray) {
						// push new number object
						copyTo.push(new Number(copyWhat));
					} else {
						// create new number object
						copyTo[copyWhatName] = new Number(copyWhat);
					};
					
				// clone boolean object
				} else if (copyWhat instanceof Boolean) { 
					if (isCopyToAnArray) {
						// push new boolean object
						if (copyWhat === true) {
							copyTo.push(new Boolean(true));
						} else {
							copyTo.push(new Boolean(false));
						};
					} else {
						// create new boolean object
						if (copyWhat === true) {
							copyTo[copyWhatName] = new Boolean(true);
						} else {
							copyTo[copyWhatName] = new Boolean(false);
						};
					};
					
				// clone date object
				} else if (copyWhat instanceof Date) { 
					if (isCopyToAnArray) {
						// push new date object
						copyTo.push(new Date(copyWhat));
					} else {
						// create new date object
						copyTo[copyWhatName] = new Date(copyWhat);
					};
					
				// clone primitive values
				} else if (typeof copyWhat === 'string' || typeof copyWhat === 'number' || typeof copyWhat === 'boolean') { 
					if (isCopyToAnArray) {
						// push value as is
						copyTo.push(copyWhat);
					} else {
						// copy value as is
						copyTo[copyWhatName] = copyWhat;
					};
					
				// clone literal object
				} else if (isLiteral(copyWhat)) {
					// clone each map item
					var cloneInto = {};
					$.each(copyWhat, function(mapItemName, mapItemToCopy) {
						cloneInto = doClone(cloneInto, mapItemToCopy, mapItemName, objectCloneHandler); 
					});
					
					if (isCopyToAnArray) {
						if (!copyWhatName) { // root object's case
							copyTo = [cloneInto];
						} else {
							copyTo.push(cloneInto);
						};
					} else {
						if (!copyWhatName) { // root object's case
							copyTo = cloneInto;
						} else {
							copyTo[copyWhatName] = cloneInto;
						};
					};
				
				// clone null value
				} else if (isNull(copyWhat)) {
					if (isCopyToAnArray) {
						// push null
						copyTo.push(null);
					} else {
						// copy null
						copyTo[copyWhatName] = null;
					};
				
				// clone an object or anything else
				} else { 
					// copy as is
					// reasons: we may call constructor but parameters and internal state could be an issue
					//          so it's better to remain purist - clones everything except objects
					//			and to handle such scenarios call handler if user has defined one
					if (isFunction(objectCloneHandler)) {
						// give user's handler a chance to clone object
						try {
							var clonedObject = objectCloneHandler(copyTo, copyWhatName, copyWhat);
							if (clonedObject) {
								if (isCopyToAnArray) {
									// push cloned object
									copyTo.push(clonedObject);
								} else {
									// use cloned object
									copyTo[copyWhatName] = clonedObject;
								};
							} else {
								if (isCopyToAnArray) {
									// use same object
									// note: this is the same object reference
									copyTo.push(copyWhat);			
								} else {
									// use same object
									// note: this is the same object reference
									copyTo[copyWhatName] = copyWhat;			
								};
							};
						} catch (ex) {
							$f.error("Custom clone handler failed to clone '" + copyWhatName + "'.", false, false, ex);
						};
					} else {
						if (isCopyToAnArray) { 
							// copy object as is
							// note: this is the same object reference
							copyTo.push(copyWhat);
						} else {
							// copy object as is
							// note: this is the same object reference
							copyTo[copyWhatName] = copyWhat;
						};
					};
				};
				
				// return
				return copyTo;
			};
			
			// perform cloning in a new empty object
			return doClone({}, object, "", customCloneSupportHandler);
		}
	};
	
	// gets a new guid
	// returns (string): new guid
	this.guid = function() { 
		// generate four random hex digits
		var S4 = function() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		};

		// generate a pseudo-GUID by concatenating random hexadecimal
		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: objectFactory
  *	 Target: $f.utils
  *  Dependencies: 
  *		- $f
  *		- $f.utils
  *  Functionality:
  *		- this adds object creation factory utility
  *
  */
(function($f) { $f.extend.feature("objectFactory", "utils", "c4dbb990-c203-4aba-91aa-52116e74ebe3", function(self) {
	
	"use strict"; 
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "Object Factory",
		description: "Adds object creation factory utility."
	};	
	
	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// object operations
	this.object = {
		// general purpose extensible (via features) factory implementation
		factory: {
			// checks if given object is instance of given class
			// params:
			//	object (object): object instance to check for
			//	className (string): name of the class to check against
			// returns (boolean): true, if instance of, false otherwise
			isInstanceOf: function(object, className) {
				// get class
				var classFunc = self.object.factory.classes[className];	
				
				// check instance of
				var isSuccess = false;
				if (isFunction(classFunc)) {
					isSuccess = (object instanceof classFunc);
				};
				
				// return
				return isSuccess;			
			},
		
			// factory method implementation
			// params:
			//	className (string): className for which instance is required
			//  args (array): original arguments array
			// returns (object): instance of created object, null otherwise
			create: function(className, args) {
				// get class
				var classFunc = self.object.factory.classes[className];
				
				// create instance
				var object = null;
				if (isFunction(classFunc)) {
					var F = function() {
						return classFunc.apply(this, args)
					};
					F.prototype = classFunc.prototype;
					object = new F();
				};
				
				// return
				return object;
			},
			
			// shortcut instanceof check methods
			instanceOf: {
			},
		
			// shortcuts factory methods
			getNew: {
			},
		
			// class definitions
			classes: {
			}
		}	
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: properties
  *	 Target: $f.utils
  *  Dependencies: 
  *		- $f
  *		- $f.utils
  *  Functionality:
  *		- this adds properties creation support for objectFactory in utils
  *
  */
(function($f) { $f.extend.feature("properties", "utils", "2df66f94-7be2-448a-b5c7-9a8eba37a7e4", function(self) {
	
	"use strict"; 
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "Properties",
		description: "Adds basic property definitions in object creation factory utility."
	};	
	
	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// object operations
	this.object = {
		// general purpose extensible (via features) factory implementation
		factory: {
			// shortcut instanceof check methods
			instanceOf: {
				// check if given object is an instance of property class
				// params:
				//	object (object): object instance to check for
				// returns (boolean): true, if instance of, false otherwise				
				property: function(object) {
					// return
					return self.object.factory.isInstanceOf(object, "property");
				},
				
				// check if given object is an instance of readOnlyProperty class
				// params:
				//	object (object): object instance to check for
				// returns (boolean): true, if instance of, false otherwise
				readOnlyProperty: function(object) {
					// return
					return self.object.factory.isInstanceOf(object, "readOnlyProperty");
				},
				
				// check if given object is an instance of varProperty class
				// params:
				//	object (object): object instance to check for
				// returns (boolean): true, if instance of, false otherwise				
				varProperty: function(object) {
					// return
					return self.object.factory.isInstanceOf(object, "varProperty");
				}
			},
		
			// shortcuts factory methods
			getNew: {
				// creates and return a new instance of property class
				// params:
				//  args (...): arguments any number of
				// returns (object): instance of created object, null otherwise					
				property: function() {
					// return
					return self.object.factory.create("property", arguments);
				},
				
				// creates and return a new instance of readOnlyProperty class
				// params:
				//  args (...): arguments any number of
				// returns (object): instance of created object, null otherwise				
				readOnlyProperty: function() {
					// return
					return self.object.factory.create("readOnlyProperty", arguments);
				},
				
				// creates and return a new instance of varProperty class
				// params:
				//  args (...): arguments any number of
				// returns (object): instance of created object, null otherwise					
				varProperty: function() {
					// return
					return self.object.factory.create("varProperty", arguments);
				}
			},
		
			// class definitions
			classes: {
				// property class definition
				property: function(value, getter, setter, changeEventName) { 
					var _value = value; 
					var _getter = getter; 
					var _setter = setter; 
					var _changeEventName = changeEventName; 
					this.get = function() { 
						return ((_getter) ? _getter() : _value); 
					};  
					this.set = function(value) { 
						var oldValue = _value; 
						_value = ((_setter) ? _setter(value) : value); 
						if (oldValue !== _value) { 
							if ($f.bus && _changeEventName) { 
								$f.bus.publish(_changeEventName, [_value]) 
							} 
						}; 
					}; 
				},
				
				// readOnlyProperty class definition
				readOnlyProperty: function(value, getter) { 
					var _value = value; 
					var _getter = getter; 
					this.get = function() { 
						return ((_getter) ? _getter() : _value); 
					}; 
				},
				
				// varProperty class definition
				varProperty: function(plugin, varName, getter) { 
					var _plugin = plugin; 
					var _varName = varName; 
					var _getter = getter; 
					this.get = function() { 
						return ((_getter) ? _getter() : _plugin.vars[_varName]); 
					}; 
				}
			}
		}	
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: dynamicExtend
  *	 Target: $f
  *  Dependencies: 
  *		- $f
  *  Functionality:
  *		- this adds dynamic extension support to core framework
  *
  */
(function($f) { $f.extend.feature("dynamicExtend", "root", "529c7242-75c5-42b5-97c4-9079d0682894", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "Dynamic Extend",
		description: "Adds dynamic extension support to core."
	};	
	
	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// interval in milliseconds that is used in setInterval for on load processing
		// this controls that extendFrom is waiting till all processes of plugin initialization and load are done
		pluginAllDoneCheckInterval: 1
	};
		
	this.FUNC_extend = {
		// load framework plugin from given plugin JS file
		// params: 
		//	pluginJSFile (string): plugin JS file that is to be loaded
		//  qualifiedPluginName (string): complete qualified plugin name with namespace (e.g., com.microsoft.aop)
		//  type (string): type of plugin
		//				   "module", "pane", "feature", "plugin", "" (empty means "plugin")
		//	callback (function): Optional. function to be called on load, signature should be void callBackFunc(data, isError);
		// returns (void):
		fromFile: function(pluginJSFile, qualifiedPluginName, type, callback) {
			// arguments fix
			if (isFunction(type)) {
				callback = type;
				type = "plugin";
			} else if (isString(type)) {
				if (type === "") {
					type = "plugin";
				};
			};
		
			// define a callback that needs to be called after plugin js is loaded
			var onPluginJSLoadComplete = function(data, isError) {
				// check if it is loaded
				var plugin = null;
				var pluginPath = "";
				if (!isError) {
					try {
						if (data.type === "feature") {
							// perform callback
							// NOTE: In case of features, callback is fired even before it might have completed 
							// its include processing for instantiated instances, the reason for this is that 
							// while there is always one instance of a plugin, a feature may have multiple 
							// instances now (and later as well, when new target plugins are loaded) and all 
							// instamces will finish their loading differently - because they can be configured
							// differently in their respective pre-init.
							if (isFunction(data.callback)) {
								data.callback(pluginJSFile, isError);
							};						
						} else if (!isEmpty(data.qualifiedPluginName)) {
							// get plugin by qualified plugin name
							plugin = self.get.plugin.byQualifiedName(data.qualifiedPluginName, data.type);
									
							// set file name in plugin, if found
							if (plugin) {
								plugin.handle.file = pluginJSFile;
							};
						};
					} catch (ex) {
						self.error("Failed to load '" + pluginPath + "'.", false, false, ex);
					};
				};

				if (data.type !== "feature") {
					// controlled call forward - this is required to ensure that we release from here only when 
					// everything related to plugin load is done
					if (!isError && plugin && isFunction(data.callback)) {
						$.doTimeout("allDoneCheck", self.vars.pluginAllDoneCheckInterval, function() {
							// check if everything is done
							var isRemaining = !(plugin.handle.isIncludeProcessed && 
												($f.i18n ? plugin.handle.isResourcesProcessed : true) && 
												($f.state.isAllBatchReady ? plugin.handle.isReady : true));
												// this last condition is for scenarios when all plugins are ready
												// and this is being extended later on, in that case wait for it's
												// ready status as well | otherwise ready is not called and will be
												// called later - so it's ok (hence true)
							
							if (!isRemaining) { 
								// perform callback
								if (isFunction(data.callback)) {
									data.callback(pluginJSFile, false);
								};

								// done
								return false; // so it does not poll
							} else {
								// return
								return true; // so it polls again											
							};
						});		
					} else {
						// perform callback
						if (isFunction(data.callback)) {
							data.callback(pluginJSFile, true);
						};				
					};
				};
			};
			
			// load JS file, plugin will be automatically loaded
			if ($f.document) {
				$f.document.JS.loadASync(pluginJSFile, {qualifiedPluginName: qualifiedPluginName, type: type, callback: callback}, onPluginJSLoadComplete);
			} else {
				if (isFunction(callback)) {
					callback("", true);
				};
			};
		},
		
		
		FUNC_feature: {
			// forwards to extend
			fromFile: function(pluginJSFile, callback) {
				// forward
				return self.extend.fromFile(pluginJSFile, "", "feature", callback);
			}
		}
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: fileInclude
  *	 Target: $f.document
  *  Dependencies: 
  *		- $f
  *		- $f.document
  *  Functionality:
  *		- this add file include support feature to document
  *		- it does process other plugins to process following properties of a plugin, if defined.
  *			> include
  *		- it does process some other file inclusion properties as well, such as theme's styles, layout
  *		  styles, theme includes and app's plugins, etc.
  *
  */
(function($f) {	$f.extend.feature("fileInclude", "document", "e484bcf0-4fda-4984-92c5-f4170c439d1d", function(self) {

	"use strict";

	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvv PRIVATE VARS AND FUNCTIONS  vvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

	// called when load file is completed
	var onIncludeComplete = function(isFeatureIncludeProcess, extenderInstance, plugin, index, file, name, isProcessed, isLoaded, isError, files) {
		// mark loaded
		if (isFeatureIncludeProcess) {
			extenderInstance.featureInclude[index].isProcessed = isProcessed;
			extenderInstance.featureInclude[index].isLoaded = isLoaded;							
		} else {
			plugin.include[index].isProcessed = isProcessed;
			plugin.include[index].isLoaded = isLoaded;								
		};
		
		// add trace message
		if (isProcessed && isLoaded && !isError) {
			if (isFeatureIncludeProcess) {
				$f.trace("File '" + file + "' is loaded against definition '" + name + "' in plugin '" + plugin.handle.name + "' for feature '" + extenderInstance.featureHandle.name + "' at index '" + index.toString() + "'. Error: " + isError.toString());
			} else {
				$f.trace("File '" + file + "' is loaded against definition '" + name + "' in plugin '" + plugin.handle.name + "' at index '" + index.toString() + "'. Error: " + isError.toString());
			};
		} else if (!isProcessed && !isLoaded && !isError) {
			if (isFeatureIncludeProcess) {
				$f.trace("File '" + file + "' defined against definition '" + name + "' in plugin '" + plugin.handle.name + "' for feature '" + extenderInstance.featureHandle.name + "' at index '" + index.toString() + "' is skipped as its type is unknown.");
			} else {
				$f.trace("File '" + file + "' defined against definition '" + name + "' in plugin '" + plugin.handle.name + "' at index '" + index.toString() + "' is skipped as its type is unknown.");
			};
		} else if (isProcessed && !isLoaded && !isError) {
			if (isFeatureIncludeProcess) {
				$f.trace("File '" + file + "' defined against definition '" + name + "' in plugin '" + plugin.handle.name + "' for feature '" + extenderInstance.featureHandle.name + "' at index '" + index.toString() + "' is not loaded as its include condition was not satisfied.");
			} else {
				$f.trace("File '" + file + "' defined against definition '" + name + "' in plugin '" + plugin.handle.name + "' at index '" + index.toString() + "' is not loaded as its include condition was not satisfied.");
			};
		};

		// call include for next file
		includeFile(files, isFeatureIncludeProcess);	
	};
	
	// load file
	var includeFile = function(files, isFeatureIncludeProcess) {
		// stop if files are over
		if (files.length === 0) {
			return;
		};
	
		// pick first item
		var plugin = files[0].plugin;
		var extenderInstance = (isFeatureIncludeProcess ? files[0].extenderInstance : null );
		var name = files[0].name;
		var file = files[0].file;
		var index = files[0].index;
		var condFunc = files[0].cond;
		
		// remove first item
		files.splice(0, 1);

		// process only if defined condition is satisfied, if any
		var isProcess = true;
		if (isFunction(condFunc)) {
			try {
				isProcess = condFunc();
			} catch (ex) {
				isProcess = false;
				if (isFeatureIncludeProcess) {
					$f.error("Failed to check include condition for '" + name + "' in plugin '" + plugin.handle.name + "' for feature '" + extenderInstance.featureHandle.name + "'.", false, false, ex);
				} else {
					$f.error("Failed to check include condition for '" + name + "' in plugin '" + plugin.handle.name + "'.", false, false, ex);
				};
			};
		};
		
		if (isProcess) {
			// get file type
			var fileType = file.substring(file.lastIndexOf(".") + 1).toLowerCase(); // get rest of characters after last "."
			
			// check if this file is any of the dynamic html end points 
			// which will serve dynamic html from server
			if ($f.config.options.dynamicHtmlEndPoints.toLowerCase().indexOf("." + fileType + ";") !== -1) {
				// in this context, html means this will be a dynamic template
				// therefore mark it to be treated as html
				fileType = "html";
			};
			
			// process file type
			switch(fileType) {
				case "js": {
					self.JS.loadASync(file, name, function(name, isError) {
						// include completed
						onIncludeComplete(isFeatureIncludeProcess, extenderInstance, plugin, 
										  index, file, name, true, !isError, isError, files);
					});
					break;
				};
				case "css": {
					self.CSS.loadASync(file, name, function(name, isError) {
						// include completed
						onIncludeComplete(isFeatureIncludeProcess, extenderInstance, plugin, 
										  index, file, name, true, !isError, isError, files);
					});
					break;
				};
				case "html": {
					self.HTML.template.loadASync(plugin, name, file, name, function(name, isError) {
						// include completed
						onIncludeComplete(isFeatureIncludeProcess, extenderInstance, plugin, 
										  index, file, name, true, !isError, isError, files);
					});
					break;
				};
				default: {
					// unknown file type - mark not-loaded
					// include completed
					onIncludeComplete(isFeatureIncludeProcess, extenderInstance, plugin, 
									  index, file, name, false, false, false, files);				
					break;
				};		
			};		
		} else {
			// mark as processed (without loading it)
			// include completed
			onIncludeComplete(isFeatureIncludeProcess, extenderInstance, plugin, 
							  index, file, name, true, false, false, files);			
		};
	};	
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "File Include",
		description: "Add files include functionality support to document."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// interval in milliseconds that is used in setInterval before plugin's load processing is done
		// this controls that onInit is called only when all files in includeFiles of plugin are loaded
		pluginLoadCheckInterval: 2
	};
	
	// load all files mentioned in given extenderInstance object asynchronously or synchronously, as applicable
	// specific file types: JS, CSS, Template and any other server file types which server dynamic html
	// params:
	//	extenderInstance (object): feature object for which files are to be included
	// returns (void):
	this.includeFeatureFiles = function(extenderInstance) {
		if (extenderInstance && extenderInstance.featureInclude && isArray(extenderInstance.featureInclude)) {
			// add required functions to featureInclude array
			extenderInstance.featureInclude["isProcessed"] = function(name) { 
				var isProcessed = false;
				name = name.toLowerCase();
				$.each(extenderInstance.featureInclude, function(i, item) { 
					if (item.name.toLowerCase() === name) {
						isProcessed = item.isProcessed;
						return false; // break
					};
				});
				return isProcessed;
			};
			extenderInstance.featureInclude["isLoaded"] = function(name) { 
				var isLoaded = false;
				name = name.toLowerCase();
				$.each(extenderInstance.featureInclude, function(i, item) { 
					if (item.name.toLowerCase() === name) {
						isLoaded = item.isLoaded;
						return false; // break
					};
				});
				return isLoaded;
			};

			// begin loading all in sequence - one by one - to avoid any dependency issues between files
			var files = [];
			var name = "";
			var file = "";
			var cond = null;
			var lengthSoFar = 0;
			$.each(extenderInstance.featureInclude, function(i, def) {
				// read file and name
				name = def.name;
				file = def.file;
				if (isFunction(def.cond)) {
					cond = def.cond;
				} else {
					cond = null;
				};
				
				// add a property to check load status
				def["isProcessed"] = false;
				def["isLoaded"] = false;

				// add to list
				files.push({extenderInstance: extenderInstance, plugin: extenderInstance.featureHandle.host, index: i, name: name, file: file, cond: cond});
				
				// add length
				lengthSoFar++;
			});
			
			// include files in sequence (this will go in a recursive call - till all items from files array are removed)
			includeFile(files, true);
			
			// poll till all files are included
			var traceCount = -1;
			var waitingBecause = "";
			$.doTimeout(extenderInstance.featureHandle.id + "___" + extenderInstance.featureHandle.host.handle.id + "_loadCheck", self.vars.pluginLoadCheckInterval, function() {
				// check
				var isPollAgain = true;
				var count = 0;
				var loaded = 0;
				traceCount = traceCount + 1
				if (traceCount > 250) {
					traceCount = 0;
				};
				$.each(extenderInstance.featureInclude, function(i, def) {
					count++;
					if (def.isProcessed) {
						loaded++;
					} else {
						waitingBecause = "Waiting to load: '" + def.file + "'.";
						return false; // break
					};
				});
				
				// set flag if all are loaded
				if (count === loaded) {
					// do not poll again
					isPollAgain = false;
					
					// call on feature include complete
					extenderInstance.featureHandle.onFeatureIncludeComplete();
				} else {
					// add to trace and show in message
					if (traceCount === 0) {
						$f.trace(waitingBecause);
					};
				};				
				
				// return
				return isPollAgain;
			});	
		} else {
			// call on feature include complete
			extenderInstance.featureHandle.onFeatureIncludeComplete();	
		};	
	};
	
	// load all files mentioned in given include object asynchronously or synchronously, as applicable
	// specific file types: JS, CSS, Template and any other server file types which server dynamic html
	// params:
	//	plugin (object): plugin object for which files are to be included
	// returns (void):
	this.includeFiles = function(plugin) {
		// files to be included in sequence
		var files = [];
		var name = "";
		var file = "";
		var cond = null;
		var lengthSoFar = 0;
	
		if (plugin.include && isArray(plugin.include)) {
			// begin loading all in sequence - one by one - to avoid any dependency issues between files
			$.each(plugin.include, function(i, def) {
				// read file and name
				name = def.name;
				file = def.file;
				if (isFunction(def.cond)) {
					cond = def.cond;
				} else {
					cond = null;
				};
				
				// add a property to check load status
				def["isProcessed"] = false;
				def["isLoaded"] = false;

				// add to list
				files.push({plugin: plugin, index: i, name: name, file: file, cond: cond});
				
				// add length
				lengthSoFar++;
			});
		} else {
			// define an empty array
			plugin["include"] = [];
		};
		
		// add required functions to include array
		plugin.include["isProcessed"] = function(name) { 
			var isProcessed = false;
			name = name.toLowerCase();
			$.each(plugin.include, function(i, item) { 
				if (item.name.toLowerCase() === name) {
					isProcessed = item.isProcessed;
					return false; // break
				};
			});
			return isProcessed;
		};
		plugin.include["isLoaded"] = function(name) { 
			var isLoaded = false;
			name = name.toLowerCase();
			$.each(plugin.include, function(i, item) { 
				if (item.name.toLowerCase() === name) {
					isLoaded = item.isLoaded;
					return false; // break
				};
			});
			return isLoaded;
		};		
		
		// if this is app type plugin, include "devPluigns" (if required), statically defined  
		// application plugins in "app.plugins" and dynamically defined "fluidPlugins" list as well 
		// after included files
		if (plugin.handle.isApp()) {
			if ($f.config.options.isDebug && fluidOptions && fluidOptions.devPlugins && isArray(fluidOptions.devPlugins)) {
				// dev tool plugins defined externally
				$.each(fluidOptions.devPlugins, function(i, def) {
					// read file and name
					name = def.file.replace(/./g, "_"); // replace all . with _  
					file = def.file.replace(/\\/g, "/"); // replace all \ with /  
					cond = null;

					// add a property to check load status
					def["isProcessed"] = false;
					def["isLoaded"] = false;
				
					// only js files are considered, since conditional plugins are only JS files
					var fileType = file.substring(file.lastIndexOf(".") + 1); // get rest of characters after last "."					
					if (fileType.toLowerCase() === "js") {
						// update name, so that it can be added to include list without any possible conflicts
						var updatedName = "________devTool_plugin_" + name;

						// length (to know the index where this item will be pushed in include array)
						lengthSoFar++;
						
						// add to list
						files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
						
						// also add to include list - so that load mark can be added below
						// although this will pollute the include object - but since this is only
						// temporary in nature, this does not create any harm and no logic change
						// is required below - to check if all files are loaded
						plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
					};				
				});
			};
			
			// plugins defined at application level
			if (plugin.plugins) {
				$.each(plugin.plugins, function(i, def) {
					// read file and name
					name = def.name;
					file = def.file;
					if (isFunction(def.cond)) {
						cond = def.cond;
					} else {
						cond = null;
					};				
				
					// add a property to check load status
					def["isProcessed"] = false;
					def["isLoaded"] = false;
				
					// only js files are considered, since plugins are only JS files
					var fileType = file.substring(file.lastIndexOf(".") + 1); // get rest of characters after last "."					
					if (fileType.toLowerCase() == "js") {
						// update name, so that it can be added to include list without any possible conflicts
						var updatedName = "________plugin_" + name;

						// length (to know the index where this item will be pushed in include array)
						lengthSoFar++;
						
						// add to list
						files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
						
						// also add to include list - so that load mark can be added below
						// although this will pollute the include object - but since this is only
						// temporary in nature, this does not create any harm and no logic change
						// is required below - to check if all files are loaded
						plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
					};
				});		
			};
		
			// plugins defined dynamically 
			if (fluidOptions && fluidOptions.fluidPlugins) {
				$.each(fluidOptions.fluidPlugins, function(i, def) {
					// read file and name
					name = def.file.replace(/./g, "_").replace(/\*/g, "_"); // replace all . and * with _  
					file = def.file;
					cond = null;
				
					// add a property to check load status
					def["isProcessed"] = false;
					def["isLoaded"] = false;
				
					// only js files are considered, since plugins are only JS files
					var fileType = file.substring(file.lastIndexOf(".") + 1); // get rest of characters after last "."					
					if (fileType.toLowerCase() == "js") {
						// update name, so that it can be added to include list without any possible conflicts
						var updatedName = "________plugin_external_" + name;

						// length (to know the index where this item will be pushed in include array)
						lengthSoFar++;
						
						// add to list
						files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
						
						// also add to include list - so that load mark can be added below
						// although this will pollute the include object - but since this is only
						// temporary in nature, this does not create any harm and no logic change
						// is required below - to check if all files are loaded
						plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
					};
				});		
			};				
		};
			
		// if this is master page type plugin, include following other files as well after included files
		// include theme's include files
		// include theme's layout's styles
		// include master page's layout's styles
		// include page's layout's styles
		if (plugin.handle.isMaster() && !plugin.handle.isDefaultMaster()) {
			// theme's files
			if ($f.app && $f.app.theme) {
				// theme's include files
				var theme = $f.app.theme();
				if (theme && theme.include && isArray(theme.include)) {
					$.each(theme.include, function(i, def) {
						// read file and name
						name = def.name;
						file = def.file;
						if (isFunction(def.cond)) {
							cond = def.cond;
						} else {
							cond = null;
						};	
						
						// add a property to check load status
						def["isProcessed"] = false;
						def["isLoaded"] = false;

						// update name, so that it can be added to include list without any possible conflicts
						var updatedName = "________theme_" + name;

						// length (to know the index where this item will be pushed in include array)
						lengthSoFar++;
						
						// add to list
						files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
						
						// also add to include list - so that load mark can be added below
						// although this will pollute the include object - but since this is only
						// temporary in nature, this does not create any harm and no logic change
						// is required below - to check if all files are loaded
						plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
					});
				};
				
				// theme's layout's styles
				if (theme && theme.layout) {
					var themeStyles = $f.page.p.getStyles(theme.layout);
					$.each(themeStyles, function(i, def) {
						// read file and name
						name = def.name;
						file = def.file;
						if (isFunction(def.cond)) {
							cond = def.cond;
						} else {
							cond = null;
						};	
						
						// add a property to check load status
						def["isProcessed"] = false;
						def["isLoaded"] = false;
			
						// update name, so that it can be added to include list without any possible conflicts
						var updatedName = "________theme_style_" + name;

						// length (to know the index where this item will be pushed in include array)
						lengthSoFar++;
						
						// add to list
						files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
						
						// also add to include list - so that load mark can be added below
						// although this will pollute the include object - but since this is only
						// temporary in nature, this does not create any harm and no logic change
						// is required below - to check if all files are loaded
						plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
					});
				};
			};
			
			// master layout styles
			if ($f.master && $f.master.config && $f.master.config.layout) {
				var masterStyles = $f.page.p.getStyles($f.master.config.layout);
				$.each(masterStyles, function(i, def) {
					// read file and name
					name = def.name;
					file = def.file;
					if (isFunction(def.cond)) {
						cond = def.cond;
					} else {
						cond = null;
					};	
							
					// add a property to check load status
					def["isProcessed"] = false;
					def["isLoaded"] = false;

					// update name, so that it can be added to include list without any possible conflicts
					var updatedName = "________master_style_" + name;

					// length (to know the index where this item will be pushed in include array)
					lengthSoFar++;
					
					// add to list
					files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
					
					// also add to include list - so that load mark can be added below
					// although this will pollute the include object - but since this is only
					// temporary in nature, this does not create any harm and no logic change
					// is required below - to check if all files are loaded
					plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
				});		
			};
			
			// page layout styles
			if ($f.page.config && $f.page.config.layout) {
				var pageStyles = $f.page.p.getStyles($f.page.config.layout);
				$.each(pageStyles, function(i, def) {
					// read file and name
					name = def.name;
					file = def.file;
					if (isFunction(def.cond)) {
						cond = def.cond;
					} else {
						cond = null;
					};
					
					// add a property to check load status
					def["isProcessed"] = false;
					def["isLoaded"] = false;

					// update name, so that it can be added to include list without any possible conflicts
					var updatedName = "________page_style_" + name;

					// length (to know the index where this item will be pushed in include array)
					lengthSoFar++;
					
					// add to list
					files.push({plugin: plugin, index: (lengthSoFar - 1), name: updatedName, file: file, cond: cond});
					
					// also add to include list - so that load mark can be added below
					// although this will pollute the include object - but since this is only
					// temporary in nature, this does not create any harm and no logic change
					// is required below - to check if all files are loaded
					plugin.include.push({name: updatedName, file: file, isLoaded: false, isProcessed: false, cond: cond});
				});	
			};
		};			
		
		// load, if any sequence is defined
		if (files.length !== 0) {
			// include files in sequence (this will go in a recursive call - till all items from files array are removed)
			includeFile(files, false);
			
			// poll till all files are included
			var traceCount = -1;
			var waitingBecause = "";
			$.doTimeout(plugin.handle.id + "_loadCheck", self.vars.pluginLoadCheckInterval, function() {
				// check
				var isPollAgain = true;
				var count = 0;
				var loaded = 0;
				traceCount = traceCount + 1
				if (traceCount > 250) {
					traceCount = 0;
				};
				$.each(plugin.include, function(i, def) {
					count++;
					if (def.isProcessed) {
						loaded++;
					} else {
						waitingBecause = "Waiting to load: '" + def.file + "'.";
						return false; // break
					};
				});
				
				// set flag if all are loaded
				if (count === loaded) {
					// do not poll again
					isPollAgain = false;
					
					// call on include complete
					plugin.handle.onIncludeComplete();
				} else {
					// add to trace and show in message
					if (traceCount === 0) {
						$f.trace(waitingBecause);
						window.status = waitingBecause;
					};
				};				
				
				// return
				return isPollAgain;
			});	
		} else {
			// call on include complete
			plugin.handle.onIncludeComplete();		
		};
	};	
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: document
  *  Dependencies: 
  *		- $f
  *  Functionality:
  *		- this plugin provides core document processing.
  */
(function($f) { $f.extend.system("document", "cd45574f-2307-48b1-a9ce-90d7692289a9", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// loads stcrural elements in startup html
	var loadStartupHtmlStructure = function() {
		// load styles required by this structure
		self.CSS.styles.load("baseStructureCSS", '' +
			'#root { width: 100%; height: 100%; position: absolute; overflow: auto; } \n');
	
		// load basic internally controlled structure for startup html
		var structureHtml = '' + 
		'<div id="root">' +
			'<div id="templates"></div>' + 
			'<div id="unstructuredBody"></div>' +
		'</div>';

		// add root structure and anything that is in special div named "body", 
		// move it inside "unstructuredBody"
		if ($f.config.options.isSupressAutoBodyVisible) {
			$("body").append(structureHtml).find("#" + $f.env.container.body()).detach().prependTo("#" + $f.env.container.unstructuredBody());
		} else {
			$("body").append(structureHtml).find("#" + $f.env.container.body()).show().detach().prependTo("#" + $f.env.container.unstructuredBody());
		};
	};
	
	// load template html content in element
	var loadTemplateContent = function(htmlFile, templateName, templateHTMLContent, plugin, data, callback) {
		if (!templateHTMLContent) {
			$f.error("Cannot load template '" + htmlFile + "'. ", true, false);
			
			// callback
			if (isFunction(callback)) {
				callback(data, true);
			};							
		} else {
			var elementId = $f.env.container.templates();
			var element = $("#" + elementId);
			if (element.length === 0) {
				$f.error("Cannot load template '" + htmlFile + "'. Templates container is missing.", true, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, true);
				};								
			} else {
				// pack in a DOM element
				var templateDOMitem = "";
				if ($f.dataBinder) {
					// let data binder pack template the way it wants
					templateDOMitem = $f.dataBinder.packTemplate(templateName, templateHTMLContent);
				} else {
					// default approach
					// wrap template in a named element and then add to container
					// wrapping it like this ensures that it did not get included and is reachable by given id
					var wrapperStart = $f.config.options.htmlTemplateElementDOMWrapperStart.replace("%NAME%", templateName);
					var wrapperEnd = $f.config.options.htmlTemplateElementDOMWrapperEnd;							
					templateDOMitem = wrapperStart + templateHTMLContent + wrapperEnd;
				};
				
				// process and load html
				self.HTML.load(elementId, templateDOMitem, {plugin: plugin, 
															htmlFile: htmlFile, 
															isReplace: false,
															isSkipHyperlinkInterception: true});

				// here hyperlink interception is not done intentionally
				// because these are just templates and will not be visible till
				// used by data binding
				
				// add to list
				self.vars.templates.push(templateName);
		
				// callback
				if (isFunction(callback)) {
					callback(data, false);
				};		
			};
		};
	};			
	
	// load layout html content in element
	var loadLayoutContent = function(htmlFile, htmlContent, containerElementId, plugin, data, callback) {
		if (!htmlContent) {
			$f.error("Cannot load layout '" + htmlFile + "'. ", true, false);
			
			// callback
			if (isFunction(callback)) {
				callback(data, true);
			};
		} else {
			// process and load html
			self.HTML.load(containerElementId, htmlContent, {plugin: plugin, htmlFile: htmlFile});
			
			// callback
			if (isFunction(callback)) {
				callback(data, false);
			};	
		};						
	};
					
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "Document",
		description: "Provides various document level processings."
	};

	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// load startup html structure
		loadStartupHtmlStructure();
		
		// return
		return true; 
	};
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// list of all loaded JS files
		JS: [],
		
		// list of all loaded CSS files
		CSS: [],
		
		// list of all loaded templates
		templates: [], 

		// dynamically loaded loose styles
		styles: [],
		
		// after this interval, if file could not be loaded
		// it will signal it as error
		JsCssLoadCheckFallbackCallAfter: 3000
	};
		
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 75
	};
	
	// JS file operations
	this.JS = {
		// check if given CSS file is loaded
		// params: 
		//	jsFile (string): name of the JS file that is to be loaded	
		// returns (boolean): true, if loaded, false otherwise
		isLoaded: function(jsFile) {
			// check if already loaded
			var isFound = false;
			var jsFileLC = jsFile.toLowerCase();
			$.each(self.vars.JS, function(i, jsUrl) {
				if (jsUrl.toLowerCase() === jsFileLC) {
					isFound = true;
					return false; // break
				};
			});

			// return
			return isFound;
		},
		
		// loads specified JS file asynchronously in current document
		// a JS will be loaded only once if it was already loaded it is not reloaded
		// params: 
		//	jsFile (string): name of the JS file that is to be loaded
		//  data (object): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after JS file is loaded
		//						 signature of this function should be: void callBackFunc(data, isError);
		// returns (void):
		loadASync: function(jsFile, data, callback) {
			if (jsFile) {
				// convert .*. to .debug. or .min.
				if (jsFile.indexOf(".*.") !== -1) {
					if ($f.config.options.isDebug) {
						jsFile = jsFile.replace(".*.", ".debug.");
					} else {
						jsFile = jsFile.replace(".*.", ".min.");
					};
				};	
				
				// load only if not already loaded
				if (!self.JS.isLoaded(jsFile)) {
					// convert callback to wrapped callback
					var timeoutJSFallbackCheck = "backupProcessJS_" + jsFile;
					var wrappedJSCallback = function(originalCallback, data, isError) {
						// cancel fallback check
						$.doTimeout(timeoutJSFallbackCheck);
						
						// call original callback
						if (isFunction(originalCallback)) {
							originalCallback(data, isError);
						};
					};
				
					var doc = document;
					var script = doc.createElement("script")
					script.type = "text/javascript";
					script.async = false; // so it loads in order
					if (script.readyState) { //IE
						script.onreadystatechange = function () {
							if (script.readyState === "loaded" || script.readyState === "complete") {
								script.onreadystatechange = null;
								wrappedJSCallback(callback, data, false);
							};
						};
					} else { //Others
						script.onload = function () {
							script.onload = null;
							wrappedJSCallback(callback, data, false);
						};
					};
					script.src = $f.IO.folder.getResolvedPath(jsFile);

					// setup a fallback timeout, to ensure that if file could not be
					// loaded during a certain time period, it will break-out and
					// call callback with error
					// certain browsers (like chrome) stuck if file is not available
					$.doTimeout(timeoutJSFallbackCheck, self.vars.JsCssLoadCheckFallbackCallAfter, function() {
						// came here - means file is still not loaded
						// so either file does not exists and browser stuck or 
						// some other issue
						// in either case, call it an error
						if (isFunction(callback)) {
							callback(data, true);
						};

						// done
						return false; // so it does not poll
					});
					
					// this will initiate the loading
					doc.getElementsByTagName("head")[0].appendChild(script);
					
					// add to list
					self.vars.JS.push(jsFile);
				} else {
					// perform call back now
					if (isFunction(callback)) {
						callback(data, false);
					};
				};
			} else {
				// log error
				$f.error("Error loading js. File name not specified.", false, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, true);
				};	
			};
		}
	};
	
	// CSS file operations
	this.CSS = {
		// check if given CSS file is loaded
		// params: 
		//	cssFile (string): name of the CSS file that is to be loaded		
		// returns (boolean): true, if loaded, false otherwise
		isLoaded: function(cssFile) {
			// check if already loaded
			var isFound = false;
			var cssFileLC = cssFile.toLowerCase();
			$.each(self.vars.CSS, function(i, cssUrl) {
				if (cssUrl.toLowerCase() === cssFileLC) {
					isFound = true;
					return false; // break
				};
			});

			// return
			return isFound;
		},
			
		// loads specified css file in current document
		// a CSS will be loaded only once if it was already loaded it is not reloaded
		// params: 
		//	cssFile (string): name of the CSS file that is to be loaded
		//  data (object): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after CSS file is loaded
		//						 signature of this function should be: void callBackFunc(data, isError);		
		// returns (void):
		loadASync: function(cssFile, data, callback) {
			if (cssFile) {
				// convert .*. to .debug. or .min.
				if (cssFile.indexOf(".*.") !== -1) {
					if ($f.config.options.isDebug) {
						cssFile = cssFile.replace(".*.", ".debug.");
					} else {
						cssFile = cssFile.replace(".*.", ".min.");
					};
				};	

				// load only if not already loaded
				if (!self.CSS.isLoaded(cssFile)) {
					// convert callback to wrapped callback
					var timeoutFallbackCheckCSS = "backupProcessCSS_" + cssFile;
					var wrappedCSSCallback = function(originalCallback, data, isError) {
						// cancel fallback check
						$.doTimeout(timeoutFallbackCheckCSS);
						
						// call original callback
						if (isFunction(originalCallback)) {
							originalCallback(data, isError);
						};
					};
					
					var doc = document;
					var link = doc.createElement("link")
					var cssFileLink = $f.IO.folder.getResolvedPath(cssFile);
					link.setAttribute("rel", "stylesheet")
					link.setAttribute("type", "text/css")
					if (link.readyState) { //IE
						link.onreadystatechange = function () {
							if (link.readyState === "loaded" || link.readyState === "complete") {
								link.onreadystatechange = null;
								wrappedCSSCallback(callback, data, false);
							};
						};
					} else { //Others
						link.onload = function () {
							link.onload = null;
							wrappedCSSCallback(callback, data, false);
						};
					};	
					link.setAttribute("href", cssFileLink);
					
					// setup a fallback timeout, to ensure that if file could not be
					// loaded during a certain time period, it will break-out and
					// call callback with error
					// certain browsers (like chrome) stuck if file is not available
					$.doTimeout(timeoutFallbackCheckCSS, self.vars.JsCssLoadCheckFallbackCallAfter, function() {
						// came here - means file is still not loaded
						// so either file does not exists and browser stuck or 
						// some other issue
						// in either case, call it an error
						if (isFunction(callback)) {
							callback(data, true);
						};

						// done
						return false; // so it does not poll
					});
					
					// this will initiate load process
					doc.getElementsByTagName("head")[0].appendChild(link);		

					// NOTE: hack for cases where onload is not fired (especially Safari)
					// since in this callback, I am just setting isProcessed to true,
					// even if this is called twice in certain cases, 
					// this does not harm anything
					var img = document.createElement('img');
					img.onerror = function() {
						wrappedCSSCallback(callback ,data, false);
					};
					img.src = cssFileLink;
					
					// add to list
					self.vars.CSS.push(cssFile);
				} else {
					// perform call back now
					if (isFunction(callback)) {
						callback(data, false);
					};
				};
			} else {
				// log error
				$f.error("Error loading css. File name not specified.", false, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, true);
				};				
			};			
		},
		
		// loose style operations
		styles: {
			// check if given style id is loaded
			// params: 
			//	id (string): an id for the style element			
			// returns (boolean): true, if loaded, false otherwise
			isLoaded: function(id) {
				// check if already loaded
				var isFound = false;
				var idLC = id.toLowerCase();
				$.each(self.vars.styles, function(i, styleId) {
					if (styleId.toLowerCase() === idLC) {
						isFound = true;
						return false; // break
					};
				});	

				// return
				return isFound;
			},
			
			// loads specified css content in current document
			// params: 
			//	id (string): an id for the style element
			//	css (string): valid css string that will be added to head under a <style> tag
			// returns (void):
			load: function(id, css) {
				// add if not already loaded
				if (!self.CSS.styles.isLoaded(id)) {
					// push to list
					self.vars.styles.push(id);
					
					// prepare style
					var wrapperStart = '<style type="text/css" id="' + id + '">';
					var wrapperEnd = '</style>';
					var cssElementContent = wrapperStart + css + wrapperEnd;
					
					// add
					$("head").append(cssElementContent); // this is a sync call
				};
			}			
		}
	};
	
	// HTML file operations
	this.HTML = {
		// load given html in specified element id
		// params:
		//	elementId (string): element id in which html is to be loaded
		//						if null or not found, it will be appended (not replaced) in body itself
		//	html (string): html string to load
		//	context (object): Optional. variety of arguments that may be required by any pre/post load processor
		// returns (void):
		load: function(elementId, html, context) {
			// get element
			var element = null;
			if (elementId) {
				element = $("#" + elementId);
			};
			
			// get context
			if (!context) {
				context = {};
			};
			
			// get replace/append
			var isReplace = true; // default is replace
			if (isDefined(context.isReplace)) {
				isReplace = context.isReplace;
			};
			
			// if not found, append in unstructuredBody or body
			if (!element || element.length === 0) {
				element = $("#" + $f.env.container.unstructuredBody()); // append directly in unstructured body (it will screw up UI, but will still show it)
				if (element.length === 0) {
					element = $("body"); // worst case
				};
				isReplace = false; // append always in these fallback cases
			};
			
			// perform pre-processing
			var isSkipPreProcessors = false;
			if (isDefined(context.isSkipAllPreProcessors)) {
				isSkipPreProcessors = context.isSkipAllPreProcessors;
			};
			if (!isSkipPreProcessors) {
				$.each(self.HTML.loadProcessors.pre, function(name, processor) {
					// process and get updated html (optionally processor might not process based on context)
					html = processor(html, context);
				});
			};
			
			// append or replace (pre-processed html) [this is sync call]
			if (element.length !== 0 && html) {
				if (isReplace) {
					element.html(html);
				} else {
					element.append(html);
				};
			};
			
			// perform post-processing
			var isSkipPostProcessors = false;
			if (isDefined(context.isSkipAllPostProcessors)) {
				isSkipPostProcessors = context.isSkipAllPostProcessors;
			};
			if (!isSkipPostProcessors) {
				$.each(self.HTML.loadProcessors.post, function(name, processor) {
					// process (optionally processor might not process based on context)
					processor(elementId, context);
				});	
			};
		},
		
		// html content pre/post load processors
		// order or processing is not guranteed
		loadProcessors: {
			// pre-load processors
			pre: {
				// processors can be added here
				// each processor function must have following signature
				// params:
				//	html (string): html to process
				//	context (object): context object that may have required information to process
				// returns (string): processed html
			},
			
			// post-load processors
			post: {
				// processors can be added here
				// each processor function must have following signature
				// params:
				//	elementId (string): DOM element id where html is just appended/replaced
				//	context (object): context object that may have required information to process
				// returns (void): 
			}
		},
		
		// layout HTML operations
		layout: {
			// load specified html file in given context
			// params:
			//	layoutFile (string): name of the layout file (with partial path) that is to be loaded
			//  containerElementId (string): id of the container where this content is to be loaded
			//  plugin (object): plugin in context (this is required while applying static bindings)
			//  data (object): data that is to be passed back to callback function
			//  callback (function): callback function that will be called after CSS file is loaded
			//						 signature of this function should be: void callBackFunc(data, isError);		
			// returns (void):
			loadASync: function(layoutFile, containerElementId, plugin, data, callback) {
				if (layoutFile) {
					// layout can be html itself - in that case it will be prefixed with "html:" token
					if ($f.utils.string.startsWith(layoutFile, "html:")) {
						// get html file path
						var htmlFile = ""; // empty in this case
						
						// get html
						var htmlContent = layoutFile.substring(5); // strip-off 'html:'
						
						// load html content
						loadLayoutContent(htmlFile, htmlContent, containerElementId, plugin, data, callback);							
					} else {
						// check if this file is any of the dynamic html end points 
						// which will serve dynamic html from server
						var fileType = layoutFile.substring(layoutFile.lastIndexOf(".") + 1).toLowerCase(); 
						var isLoadFromServer = false;
						if ($f.config.options.dynamicHtmlEndPoints.toLowerCase().indexOf("." + fileType + ";") !== -1) {
							// in this context, this means it will be a dynamic template
							// therefore bring it from server
							isLoadFromServer = true;
						};	
							
						// load as per deployment mode
						if ($f.deploymentMode.isPortable() && !isLoadFromServer) {
							// if portable version
							// get html file path
							var htmlFile = $f.IO.folder.getCompletePath(layoutFile);
							
							// get html
							var htmlContent = $f.IO.file.read(htmlFile, "");
							
							// load html content
							loadLayoutContent(htmlFile, htmlContent, containerElementId, plugin, data, callback);				
						} else {
							// any other online version
							// get html file path
							var htmlFile = $f.IO.folder.getResolvedPath(layoutFile);
							
							// get html 
							var onAJAXCallComplete = function(htmlContent, isError) {
								// load html content
								loadLayoutContent(htmlFile, htmlContent, containerElementId, plugin, data, callback);
							};
							$.ajax(htmlFile, {
								data: "",
								dataType: "html",
								error: function(jqXHR, textStatus, errorThrown) { 
									// log error
									$f.error("Error loading layout '" + layoutFile + "'. Status: '" + textStatus + "'.", false, false, errorThrown);
									
									// callback irrecpective
									onAJAXCallComplete("", true);
								},
								success: function(html, textStatus, jqXHR) {
									// callback
									onAJAXCallComplete(html, false);
								}
							});
						};
					};
				} else {
					// log error
					$f.error("Error loading layout. File name not specified.", false, false);
					
					// callback
					if (isFunction(callback)) {
						callback(data, true);
					};
				};
			}
		},
		
		// template HTML operations
		template: {
			// check if given template name is loaded
			// params: 
			//	templateName (string): name of the template to be used for template loading
			// returns (boolean): true, if loaded, false otherwise
			isLoaded: function(templateName) {
				// check if already loaded
				var isFound = false;
				// whereever this template is required to be accessed, it can be reached 
				// with templateName using normal selector
				$.each(self.vars.templates, function(i, tName) {
					if (tName === templateName) {
						isFound = true;
						return false; // break
					};
				});

				// return
				return isFound;
			},
		
			// loads specified template file in current document
			// a template will be loaded only once if it was already loaded it is not reloaded
			// params: 
			//	plugin (plugin object): plugin in context of which this template is being loaded
			//	templateName (string): name of the template to be used for template loading
			//	templateFile (string): name of the template (html) file that is to be loaded
			//  data (object): data that is to be passed back to callback function
			//  callback (function): callback function that will be called after CSS file is loaded
			//						 signature of this function should be: void callBackFunc(data, isError);		
			// returns (void):
			loadASync: function(plugin, templateName, templateFile, data, callback) {
				if (templateFile) {
					// load as per deployment mode
					if (!self.HTML.template.isLoaded(templateName)) {
						// templateFile can be html itself - in that case it will be prefixed with "html:" token
						if ($f.utils.string.startsWith(templateFile, "html:")) {
							// get html file path
							var htmlFile = ""; // empty in this case
							
							// get html
							var templateHTMLContent = templateFile.substring(5); // strip-off 'html:'
							
							// load html content
							loadTemplateContent(htmlFile, templateName, templateHTMLContent, plugin, data, callback);							
						} else {
							// check if this file is any of the dynamic html end points 
							// which will serve dynamic html from server
							var fileType = templateFile.substring(templateFile.lastIndexOf(".") + 1).toLowerCase(); 
							var isLoadFromServer = false;
							if ($f.config.options.dynamicHtmlEndPoints.toLowerCase().indexOf("." + fileType + ";") !== -1) {
								// in this context, this means it will be a dynamic template
								// therefore bring it from server
								isLoadFromServer = true;
							};					
							
							// load as per type
							if ($f.deploymentMode.isPortable() && !isLoadFromServer) {
								// if portable version
								// get html file path
								var htmlFile = $f.IO.folder.getCompletePath(templateFile);
								
								// get html
								var templateHTMLContent = $f.IO.file.read(htmlFile, "");							
								
								// load html content
								loadTemplateContent(htmlFile, templateName, templateHTMLContent, plugin, data, callback);						
							} else {
								// any other online version
								// get html file path
								var htmlFile = $f.IO.folder.getResolvedPath(templateFile);
								
								// get html 
								var onTemplateAJAXCallComplete = function(templateHTMLContent, isError) {
									// load html content
									loadTemplateContent(htmlFile, templateName, templateHTMLContent, plugin, data, callback);
								};
								$.ajax(htmlFile, {
									data: "",
									dataType: "html",
									error: function(jqXHR, textStatus, errorThrown) { 
										// log error
										$f.error("Error loading layout '" + templateFile + "'. Status: '" + textStatus + "'.", false, false, errorThrown);
										
										// callback irrecpective
										onTemplateAJAXCallComplete("", true);
									},
									success: function(html, textStatus, jqXHR) {
										// callback
										onTemplateAJAXCallComplete(html, false);
									}
								});						
							};
						};
					} else {
						// perform call back now
						if (isFunction(callback)) {
							callback(data, false);
						};					
					};
				} else {
					// log error
					$f.error("Error loading template. File name not specified.", false, false);
					
					// callback
					if (isFunction(callback)) {
						callback(data, true);
					};			
				};
			}
		}
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: files
  *  Dependencies: 
  *		- $f
  *  Functionality:
  *		- this plugin provides core file processing.
  *		- this does not process any other plugin.
  */
(function($f) { $f.extend.system("files", "ef5b399f-18b4-4517-8c74-f2df2f778225", function(self) {
	
	"use strict";

	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "Files",
		description: "Provides various type based file load/save processing."
	};
	
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 100			
	};
		
	// JSON file operations
	this.JSON = {
		// loads specified json file and returns json object
		// params: 
		//	jsonFile (string): name of the JSON file that is to be loaded
		//  charset (string): chartset with which file is encoded  (empty means ASCII)
		//  data (string): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after CSS file is loaded
		//						 signature of this function should be: void callBackFunc(data, json, isError);			
		// returns (void): 
		loadASync: function(jsonFile, charset, data, callback) {
			if (jsonFile) {
				// load content
				var loadJSONContent = function(jsonFile, jsonString) {
					var fileContent = null;
					var isError = false;
					try {
						// get object
						if (jsonString) {
							fileContent = JSON.parse(jsonString);
						};
					} catch (ex) {
						$f.error("Error loading JSON file '" + jsonFile + "'.", false, false, ex);
						fileContent = null;
						isError = true;
					};
					
					// callback
					if (isFunction(callback)) {
						callback(data, fileContent, isError);
					};				
				};

				// load as per deployment mode
				if ($f.deploymentMode.isPortable() || $f.deploymentMode.isWrapped()) {
					// if portable version
					// load async
					$.doTimeout($f.utils.guid(), 1, function() {
						// get json file path
						var fileToRead = $f.IO.folder.getCompletePath(jsonFile, true);
						
						// get json string
						var jsonString = $f.IO.file.read(fileToRead, charset);
		
						// load json content
						loadJSONContent(jsonFile, jsonString);				

						// done
						return false; // so it does not poll
					});					
				} else {
					// any other online version
					// get json file path
					var fileToRead = $f.IO.folder.getResolvedPath(jsonFile);

					// get json string 
					var onJSONAJAXCallComplete = function(jsonContent, isError) {
						// load json content
						loadJSONContent(jsonFile, jsonContent);
					};
					
					var contentType = "application/json";
					if (charset) {
						contentType = "application/json; charset=" + charset.toLowerCase();
					};
					$.ajax(fileToRead, {
						dataType: "text",
						contentType: contentType,
						error: function(jqXHR, textStatus, errorThrown) { 
							// log error
							$f.error("Error loading json '" + jsonFile + "'. Status: '" + textStatus + "'.", false, false, errorThrown);
							
							// callback irrecpective
							onJSONAJAXCallComplete("", true);
						},
						success: function(jsonContent, textStatus, jqXHR) {
							// callback
							onJSONAJAXCallComplete(jsonContent, false);
						}
					});					
				};
			} else {
				// log error
				$f.error("Error loading json. File name not specified.", false, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, null, true);
				};				
			};
		},
		
		// save specified content in specified local json file async
		// params: 
		//	jsonFile (string): name of the JSON file that is to be written to
		//  charset (string): chartset with which file is to be encoded  (empty means ASCII)
		// 	fileContent (object): json object that is to be written to the file
		//  data (string): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after CSS file is loaded
		//						 signature of this function should be: void callBackFunc(data, isError);			
		// returns (void):
		saveASync: function(jsonFile, charset, fileContent, data, callback) {
			// json string
			var fileText = JSON.stringify(fileContent, null, 4); // 4 space indentation
				
			// write async 
			$f.IO.file.writeASync(jsonFile, charset, fileText, data, callback);
		},
		
		// loads specified local json file and returns json object
		// params: 
		//	jsonFile (string): name of the JSON file that is to be loaded
		//  charset (string): chartset with which file is encoded  (empty means ASCII)
		// returns (string): returns the content of the file, if success, null if error	
		load: function(jsonFile, charset) {
			var fileContent = null;
			if (jsonFile) {
				// load
				try {
					// get complete file path
					jsonFile = $f.IO.folder.getCompletePath(jsonFile);
				
					// read
					var fileText = $f.IO.file.read(jsonFile, charset);
					
					// get object
					if (fileText) {
						fileContent = JSON.parse(fileText);
					};
				} catch (ex) {
					$f.error("Error loading JSON file '" + jsonFile + "'.", false, false, ex);
					fileContent = null;
				};
			};
			
			// return
			return fileContent;
		},
	
		// save specified content in specified local json file 
		// params: 
		//	jsonFile (string): name of the JSON file that is to be written to
		//  charset (string): chartset with which file is to be encoded  (empty means ASCII)
		// 	fileContent (object): json object that is to be written to the file
		// returns (boolean): true, if success, false, if failed
		save: function(jsonFile, charset, fileContent) {
			// save
			var success = false;
			try {
				// get complete file path
				jsonFile = $f.IO.folder.getCompletePath(jsonFile);
				
				// json string
				var fileText = JSON.stringify(fileContent, null, 4); // 4 space indentation
				
				// write
				success = $f.IO.file.write(jsonFile, charset, fileText);
			} catch (ex) {
				$f.error("Error saving JSON file '" + jsonFile + "'.", false, false, ex);
				success = false;
			};
			
			// return
			return success;
		}
	};
}); }(fluid));
/*
 * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * deployJava.js
 *
 * This file is part of the Deployment Toolkit.  It provides functions for web
 * pages to detect the presence of a JRE, install the latest JRE, and easily run
 * applets or Web Start programs.  More Information on usage of the
 * Deployment Toolkit can be found in the Deployment Guide at:
 * http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/index.html
 *
 * The "live" copy of this file may be found at :
 * http://java.com/js/deployJava.js.
 * For web pages provisioned using https, you may want to access the copy at:
 * https://java.com/js/deployJava.js.
 *
 * You are encouraged to link directly to the live copies.
 * The above files are stripped of comments and whitespace for performance,
 * You can access this file w/o the whitespace and comments removed at:
 * http://java.com/js/deployJava.txt.
 *
 */

var deployJava = function() {
    /** HTML attribute filter implementation */
    var hattrs = {
        core: [ 'id', 'class', 'title', 'style' ],
        i18n: [ 'lang', 'dir' ],
        events: [ 'onclick', 'ondblclick', 'onmousedown', 'onmouseup',
            'onmouseover', 'onmousemove', 'onmouseout', 'onkeypress',
            'onkeydown', 'onkeyup' ],
        applet: [ 'codebase', 'code', 'name', 'archive', 'object',
            'width', 'height', 'alt', 'align', 'hspace', 'vspace' ],
        object: [ 'classid', 'codebase', 'codetype', 'data', 'type',
            'archive', 'declare', 'standby', 'height', 'width', 'usemap',
            'name', 'tabindex', 'align', 'border', 'hspace', 'vspace' ]
    };

    var object_valid_attrs = hattrs.object.concat(hattrs.core, hattrs.i18n,
        hattrs.events);
    var applet_valid_attrs = hattrs.applet.concat(hattrs.core);

    // generic log function, use console.log unless it isn't available
    // then revert to alert()
    function log(message) {
        if ( ! rv.debug ) {return};

        if (console.log) {
            console.log(message);
        } else {
            alert(message);
        }
    }

    //checks where given version string matches query
    //
    //NB: assume format is correct. Can add format check later if needed
    // from dtjava.js
    function versionCheckEx(query, version) {
        if (query == null || query.length == 0) return true;

        var c = query.charAt(query.length - 1);

        //if it is not explicit pattern but does not have update version then need to append *
        if (c != '+' && c != '*' && (query.indexOf('_') != -1 && c != '_')) {
            query = query + "*";
            c = '*';
        }

        query = query.substring(0, query.length - 1);
        //if query ends with ".", "_" then we want to strip it to allow match of "1.6.*" to shorter form such as "1.6"
        //TODO: add support for match of "1.7.0*" to "1.7"?
        if (query.length > 0) {
            var z = query.charAt(query.length - 1);
            if (z == '.' || z == '_') {
                query = query.substring(0, query.length - 1);
            }
        }
        if (c == '*') {
            //it is match if version starts from it
            return (version.indexOf(query) == 0);
        } else if (c == '+') {
            //match if query string is lexicographically smaller
            return query <= version;
        }
        return false;
    }

    function getWebStartLaunchIconURL() {
        var imageUrl = '//java.com/js/webstart.png';
        try {
            // for http/https; use protocol less url; use http for all other protocol
            return document.location.protocol.indexOf('http') != -1 ? 
                imageUrl : 'http:' + imageUrl;
        } catch (err) {
            return 'http:' + imageUrl;
        }
    }

    function arHas(ar, attr) {
        var len = ar.length;
        for (var i = 0; i < len; i++) {
            if (ar[i] === attr) return true;
        }
        return false;
    }

    function isValidAppletAttr(attr) {
        return arHas(applet_valid_attrs, attr.toLowerCase());
    }

    function isValidObjectAttr(attr) {
        return arHas(object_valid_attrs, attr.toLowerCase());
    }

    /** 
     * returns true if we can enable DT plugin auto-install without chance of
     * deadlock on cert mismatch dialog
     *
     * requestedJREVersion param is optional - if null, it will be
     * treated as installing any JRE version
     * 
     * DT plugin for 6uX only knows about JRE installer signed by SUN cert.
     * If it encounter Oracle signed JRE installer, it will have chance of
     * deadlock when running with IE.  This function is to guard against this.
     */
    function enableWithoutCertMisMatchWorkaround(requestedJREVersion) {

       // Non-IE browser are okay
       if ('MSIE' != deployJava.browserName) return true;

       // if DT plugin is 10.0.0 or above, return true
       // This is because they are aware of both SUN and Oracle signature and
       // will not show cert mismatch dialog that might cause deadlock
       if (deployJava.compareVersionToPattern(deployJava.getPlugin().version, 
                                     ["10", "0", "0"], false, true)) {
          return true;
       }

       // If we got there, DT plugin is 6uX

       if (requestedJREVersion  == null) {
          // if requestedJREVersion is not defined - it means ANY.
          // can not guarantee it is safe to install ANY version because 6uX 
          // DT does not know about Oracle certificates and may deadlock
          return false;
       }

       // 6u32 or earlier JRE installer used Sun certificate
       // 6u33+ uses Oracle's certificate
       // DT in JRE6 does not know about Oracle certificate => can only 
       // install 6u32 or earlier without risk of deadlock
       return !versionCheckEx("1.6.0_33+", requestedJREVersion);
    }

    /* HTML attribute filters */

    var rv = {

    debug: null,

    /* version of deployJava.js */
    version: "20120801",

    firefoxJavaVersion: null,

    myInterval: null,
    preInstallJREList: null,
    returnPage: null,
    brand: null,
    locale: null,
    installType: null,

    EAInstallEnabled: false,
    EarlyAccessURL: null,

    // GetJava page
    getJavaURL: 'http://jdl.sun.com/webapps/getjava/BrowserRedirect?host=java.com',

    // mime-type of the DeployToolkit plugin object
    oldMimeType: 'application/npruntime-scriptable-plugin;DeploymentToolkit',
    mimeType: 'application/java-deployment-toolkit',

    /* location of the Java Web Start launch button graphic is right next to
     * deployJava.js at: 
     *    http://java.com/js/webstart.png
     *
     * Use protocol less url here for http/https support
     */
    launchButtonPNG: getWebStartLaunchIconURL(),

    browserName: null,
    browserName2: null,

    /**
     * Returns an array of currently-installed JRE version strings.
     * Version strings are of the form #.#[.#[_#]], with the function returning
     * as much version information as it can determine, from just family
     * versions ("1.4.2", "1.5") through the full version ("1.5.0_06").
     *
     * Detection is done on a best-effort basis.  Under some circumstances
     * only the highest installed JRE version will be detected, and
     * JREs older than 1.4.2 will not always be detected.
     */
    getJREs: function() {
        var list = new Array();
        if (this.isPluginInstalled()) {
            var plugin =  this.getPlugin();
            var VMs = plugin.jvms;
            for (var i = 0; i < VMs.getLength(); i++) {
                list[i] = VMs.get(i).version;
            }
        } else {
            var browser = this.getBrowser();

            if (browser == 'MSIE') {
                if (this.testUsingActiveX('1.7.0')) {
                    list[0] = '1.7.0';
                } else if (this.testUsingActiveX('1.6.0')) {
                    list[0] = '1.6.0';
                } else if (this.testUsingActiveX('1.5.0')) {
                    list[0] = '1.5.0';
                } else if (this.testUsingActiveX('1.4.2')) {
                    list[0] = '1.4.2';
                } else if (this.testForMSVM()) {
                    list[0] = '1.1';
                }
            } else if (browser == 'Netscape Family') {
                this.getJPIVersionUsingMimeType();
                if (this.firefoxJavaVersion != null) {
                    list[0] = this.firefoxJavaVersion;
                } else if (this.testUsingMimeTypes('1.7')) {
                    list[0] = '1.7.0';
                } else if (this.testUsingMimeTypes('1.6')) {
                    list[0] = '1.6.0';
                } else if (this.testUsingMimeTypes('1.5')) {
                    list[0] = '1.5.0';
                } else if (this.testUsingMimeTypes('1.4.2')) {
                    list[0] = '1.4.2';
                } else if (this.browserName2 == 'Safari') {
                    if (this.testUsingPluginsArray('1.7.0')) {
                        list[0] = '1.7.0';
                    } else if (this.testUsingPluginsArray('1.6')) {
                        list[0] = '1.6.0';
                    } else if (this.testUsingPluginsArray('1.5')) {
                        list[0] = '1.5.0';
                    } else if (this.testUsingPluginsArray('1.4.2')) {
                        list[0] = '1.4.2';
                    }
                }
            }
        }

        if (this.debug) {
            for (var i = 0; i < list.length; ++i) {
                log('[getJREs()] We claim to have detected Java SE ' + list[i]);
            }
        }

        return list;
    },

    /**
     * Triggers a JRE installation.  The exact effect of triggering an
     * installation varies based on platform, browser, and if the
     * Deployment Toolkit plugin is installed.
     *
     * The requestVersion string is of the form #[.#[.#[_#]]][+|*],
     * which includes strings such as "1.4", "1.5.0*", and "1.6.0_02+".
     * A star (*) means "any version starting within this family" and
     * a plus (+) means "any version greater or equal to this".
     * "1.5.0*" * matches 1.5.0_06 but not 1.6.0_01, whereas
     * "1.5.0+" matches both.
     *
     * installCallback is an optional argument which holds a reference
     * to a javascript callback function for reporting install status.
     *
     * If the Deployment Toolkit plugin is not present, this will just call
     * this.installLatestJRE().
     */
    installJRE: function(requestVersion, installCallback) {
        var ret = false;
        if (this.isPluginInstalled() && 
            this.isAutoInstallEnabled(requestVersion)) {
            var installSucceeded = false;
            if (this.isCallbackSupported()) {
               installSucceeded = 
                  this.getPlugin().installJRE(requestVersion, installCallback);
            } else {
               installSucceeded = this.getPlugin().installJRE(requestVersion);
            }

            if (installSucceeded) {
                this.refresh();
                if (this.returnPage != null) {
                    document.location = this.returnPage;
                }
            }
            return installSucceeded;
        } else {
            return this.installLatestJRE();
        }
    },

    /** 
     * returns true if jre auto install for the requestedJREVersion is enabled 
     * for the local system; false otherwise
     *
     * requestedJREVersion param is optional - if not specified, it will be
     * treated as installing any JRE version
     * 
     * DT plugin for 6uX only knows about JRE installer signed by SUN cert.
     * If it encounter Oracle signed JRE installer, it will have chance of
     * deadlock when running with IE.  This function is to guard against this.
     */
    isAutoInstallEnabled: function(requestedJREVersion) {
       // if no DT plugin, return false
       if (!this.isPluginInstalled()) return false;

       if (typeof requestedJREVersion  == 'undefined') {
           requestedJREVersion = null;
       }

       return enableWithoutCertMisMatchWorkaround(requestedJREVersion);

    },

    /** 
     * returns true if jre install callback is supported
     * callback support is added since dt plugin version 10.2.0 or above
     */
    isCallbackSupported: function() {
       return this.isPluginInstalled() && 
          this.compareVersionToPattern(this.getPlugin().version, 
                                       ["10", "2", "0"], false, true);
    },

    /**
     * Triggers a JRE installation.  The exact effect of triggering an
     * installation varies based on platform, browser, and if the
     * Deployment Toolkit plugin is installed.
     *
     * In the simplest case, the browser window will be redirected to the
     * java.com JRE installation page, and (if possible) a redirect back to
     * the current URL upon successful installation.  The return redirect is
     * not always possible, as the JRE installation may require the browser to
     * be restarted.
     *
     * installCallback is an optional argument which holds a reference
     * to a javascript callback function for reporting install status.
     *
     * In the best case (when the Deployment Toolkit plugin is present), this
     * function will immediately cause a progress dialog to be displayed
     * as the JRE is downloaded and installed.
     */
    installLatestJRE: function(installCallback) {
        if (this.isPluginInstalled() && this.isAutoInstallEnabled()) {
            var installSucceeded = false;
            if (this.isCallbackSupported()) {
               installSucceeded = this.getPlugin().installLatestJRE(installCallback);
            } else {
               installSucceeded = this.getPlugin().installLatestJRE();
            }
            if (installSucceeded) {
                this.refresh();
                if (this.returnPage != null) {
                    document.location = this.returnPage;
                }
            }
            return installSucceeded;
        } else {
            var browser = this.getBrowser();
            var platform = navigator.platform.toLowerCase();
            if ((this.EAInstallEnabled == 'true') &&
                (platform.indexOf('win') != -1) &&
                (this.EarlyAccessURL != null)) {

                this.preInstallJREList = this.getJREs();
                if (this.returnPage != null) {
                    this.myInterval =
                        setInterval("deployJava.poll()", 3000);
                }

                location.href = this.EarlyAccessURL;

                // we have to return false although there may be an install
                // in progress now, when complete it may go to return page
                return false;
            } else {
                if (browser == 'MSIE') {
                    return this.IEInstall();
                } else if ((browser == 'Netscape Family') &&
                           (platform.indexOf('win32') != -1)) {
                    return this.FFInstall();
                } else {
                    location.href = this.getJavaURL +
                        ((this.returnPage != null) ?
                        ('&returnPage=' + this.returnPage) : '') +
                        ((this.locale != null) ?
                        ('&locale=' + this.locale) : '') +
                        ((this.brand != null) ?
                         ('&brand=' + this.brand) : '');
                }
                // we have to return false although there may be an install
                // in progress now, when complete it may go to return page
                return false;
            }
        }
    },


    /**
     * Ensures that an appropriate JRE is installed and then runs an applet.
     * minimumVersion is of the form #[.#[.#[_#]]], and is the minimum
     * JRE version necessary to run this applet.  minimumVersion is optional,
     * defaulting to the value "1.1" (which matches any JRE).
     * If an equal or greater JRE is detected, runApplet() will call
     * writeAppletTag(attributes, parameters) to output the applet tag,
     * otherwise it will call installJRE(minimumVersion + '+').
     *
     * After installJRE() is called, the script will attempt to detect that the
     * JRE installation has completed and begin running the applet, but there
     * are circumstances (such as when the JRE installation requires a browser
     * restart) when this cannot be fulfilled.
     *
     * As with writeAppletTag(), this function should only be called prior to
     * the web page being completely rendered.  Note that version wildcards
     * (star (*) and plus (+)) are not supported, and including them in the
     * minimumVersion will result in an error message.
     */
    runApplet: function(attributes, parameters, minimumVersion) {
        if (minimumVersion == 'undefined' || minimumVersion == null) {
            minimumVersion = '1.1';
        }

        var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";

        var matchData = minimumVersion.match(regex);

        if (this.returnPage == null) {
            // if there is an install, come back here and run the applet
            this.returnPage = document.location;
        }

        if (matchData != null) {
            var browser = this.getBrowser();
            if (browser != '?') {
                if (this.versionCheck(minimumVersion + '+')) {
                    this.writeAppletTag(attributes, parameters);
                } else if (this.installJRE(minimumVersion + '+')) {
                    // after successful install we need to refresh page to pick
                    // pick up new plugin
                    this.refresh();
                    location.href = document.location;
                    this.writeAppletTag(attributes, parameters);
                }
            } else {
                // for unknown or Safari - just try to show applet
                this.writeAppletTag(attributes, parameters);
            }
        } else {
            log('[runApplet()] Invalid minimumVersion argument to runApplet():' +
                      minimumVersion);
        }
    },


    /**
     * Outputs an applet tag with the specified attributes and parameters, where
     * both attributes and parameters are associative arrays.  Each key/value
     * pair in attributes becomes an attribute of the applet tag itself, while
     * key/value pairs in parameters become <PARAM> tags.  No version checking
     * or other special behaviors are performed; the tag is simply written to
     * the page using document.writeln().
     *
     * As document.writeln() is generally only safe to use while the page is
     * being rendered, you should never call this function after the page
     * has been completed.
     */
    writeAppletTag: function(attributes, parameters) {
        var startApplet = '<' + 'applet ';
        var params = '';
        var endApplet = '<' + '/' + 'applet' + '>';
        var addCodeAttribute = true;

        if (null == parameters || typeof parameters != 'object') {
            parameters = new Object();
        }

        for (var attribute in attributes) {
            if (! isValidAppletAttr(attribute)) {
                parameters[attribute] = attributes[attribute];
            } else {
                startApplet += (' ' +attribute+ '="' +attributes[attribute] + '"');
                if (attribute == 'code') {
                    addCodeAttribute = false;
                }
            }
        }

        var codebaseParam = false;
        for (var parameter in parameters) {
            if (parameter == 'codebase_lookup') {
                codebaseParam = true;
            }
            // Originally, parameter 'object' was used for serialized
            // applets, later, to avoid confusion with object tag in IE
            // the 'java_object' was added.  Plugin supports both.
            if (parameter == 'object' || parameter == 'java_object' ||
                parameter == 'java_code' ) {
                addCodeAttribute = false;
            }
            params += '<param name="' + parameter + '" value="' +
                parameters[parameter] + '"/>';
        }
        if (!codebaseParam) {
            params += '<param name="codebase_lookup" value="false"/>';
        }

        if (addCodeAttribute) {
            startApplet += (' code="dummy"');
        }
        startApplet += '>';

        document.write(startApplet + '\n' + params + '\n' + endApplet);
    },
  

     /**
      * Returns true if there is a matching JRE version currently installed
      * (among those detected by getJREs()).  The versionPattern string is
      * of the form #[.#[.#[_#]]][+|*], which includes strings such as "1.4",
      * "1.5.0*", and "1.6.0_02+".
      * A star (*) means "any version within this family" and a plus (+) means
      * "any version greater or equal to the specified version".  "1.5.0*"
      * matches 1.5.0_06 but not 1.6.0_01, whereas "1.5.0+" matches both.
      *
      * If the versionPattern does not include all four version components
      * but does not end with a star or plus, it will be treated as if it
      * ended with a star.  "1.5" is exactly equivalent to "1.5*", and will
      * match any version number beginning with "1.5".
      *
      * If getJREs() is unable to detect the precise version number, a match
      * could be ambiguous.  For example if getJREs() detects "1.5", there is
      * no way to know whether the JRE matches "1.5.0_06+".  versionCheck()
      * compares only as much of the version information as could be detected,
      * so versionCheck("1.5.0_06+") would return true in in this case.
      *
      * Invalid versionPattern will result in a JavaScript error alert.
      * versionPatterns which are valid but do not match any existing JRE
      * release (e.g. "32.65+") will always return false.
      */
    versionCheck: function(versionPattern)
    {
        var index = 0;
        var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?(\\*|\\+)?$";

        var matchData = versionPattern.match(regex);

        if (matchData != null) {
            // default is exact version match
            // examples:
            //    local machine has 1.7.0_04 only installed
            //    exact match request is "1.7.0_05":  return false
            //    family match request is "1.7.0*":   return true
            //    minimum match request is "1.6+":    return true
            var familyMatch = false;
            var minMatch = false;

            var patternArray = new Array();

            for (var i = 1; i < matchData.length; ++i) {
                // browser dependency here.
                // Fx sets 'undefined', IE sets '' string for unmatched groups
                if ((typeof matchData[i] == 'string') && (matchData[i] != '')) {
                    patternArray[index] = matchData[i];
                    index++;
                }
            }

            if (patternArray[patternArray.length-1] == '+') {
                // + specified in request - doing a minimum match
                minMatch = true;
                familyMatch = false;
                patternArray.length--;
            } else if (patternArray[patternArray.length-1] == '*') {
                // * specified in request - doing a family match
                minMatch = false;
                familyMatch = true;
                patternArray.length--;
            } else if (patternArray.length < 4) {
                // versionPattern does not include all four version components
                // and does not end with a star or plus, it will be treated as 
                // if it ended with a star. (family match)
                minMatch = false;
                familyMatch = true;
            }

            var list = this.getJREs();
            for (var i = 0; i < list.length; ++i) {
                if (this.compareVersionToPattern(list[i], patternArray,
                                                 familyMatch, minMatch)) {
                    return true;
                }
            }

            return false;
        } else {
            var msg = 'Invalid versionPattern passed to versionCheck: ' +
                  versionPattern;
            log('[versionCheck()] ' + msg);
            alert(msg);
            return false;
        }
    },


    /**
     * Returns true if an installation of Java Web Start of the specified
     * minimumVersion can be detected.  minimumVersion is optional, and
     * if not specified, '1.4.2' will be used.
     * (Versions earlier than 1.4.2 may not be detected.)
     */
    isWebStartInstalled: function(minimumVersion) {

        var browser = this.getBrowser();
        if (browser == '?') {
            // we really don't know - better to try to use it than reinstall
            return true;
        }

        if (minimumVersion == 'undefined' || minimumVersion == null) {
            minimumVersion = '1.4.2';
        }

        var retval = false;
        var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
        var matchData = minimumVersion.match(regex);

        if (matchData != null) {
            retval = this.versionCheck(minimumVersion + '+');
        } else {
            log('[isWebStartInstaller()] Invalid minimumVersion argument to isWebStartInstalled(): ' + minimumVersion);
            retval = this.versionCheck('1.4.2+');
        }
        return retval;
    },

    // obtain JPI version using navigator.mimeTypes array
    // if found, set the version to this.firefoxJavaVersion
    getJPIVersionUsingMimeType: function() {
        // Walk through the full list of mime types.
        for (var i = 0; i < navigator.mimeTypes.length; ++i) {
            var s = navigator.mimeTypes[i].type;
            // The jpi-version is the plug-in version.  This is the best
            // version to use.
            var m = s.match(/^application\/x-java-applet;jpi-version=(.*)$/);
            if (m != null) {
                this.firefoxJavaVersion = m[1];
                // Opera puts the latest sun JRE last not first
                if ('Opera' != this.browserName2) {
                    break;
                }
            }
        }
    },

   // launch the specified JNLP application using the passed in jnlp file
   // the jnlp file does not need to have a codebase
   // this requires JRE 7 or above to work
   // if machine has no JRE 7 or above, we will try to auto-install and then launch
   // (function will return false if JRE auto-install failed)
   launchWebStartApplication: function(jnlp) {
	var uaString = navigator.userAgent.toLowerCase();

	this.getJPIVersionUsingMimeType();

	// make sure we are JRE 7 or above
        if (this.isWebStartInstalled('1.7.0') == false) {

		// perform latest JRE auto-install
  		if ((this.installJRE('1.7.0+') == false) ||
                         ((this.isWebStartInstalled('1.7.0') == false))) {
                          return false;
                }
	}

        var jnlpDocbase = null;

        // use document.documentURI for docbase
        if (document.documentURI) {
		jnlpDocbase = document.documentURI;
	}

	// fallback to document.URL if documentURI not available
        if (jnlpDocbase == null) {
		jnlpDocbase = document.URL;
	}

        var browser = this.getBrowser();

        var launchTag;

        if (browser == 'MSIE') {

            launchTag = '<' +
                'object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" ' +
		'width="0" height="0">' +
		'<' + 'PARAM name="launchjnlp" value="' + jnlp + '"' + '>' +
	        '<' + 'PARAM name="docbase" value="' + jnlpDocbase + '"' + '>' +
                '<' + '/' + 'object' + '>';
        } else if (browser == 'Netscape Family') {

            launchTag = '<' +
		'embed type="application/x-java-applet;jpi-version=' +
		this.firefoxJavaVersion + '" ' +
                'width="0" height="0" ' +
                'launchjnlp="' +  jnlp + '"' +
                'docbase="' +  jnlpDocbase + '"' +
                ' />';
        }

        if (document.body == 'undefined' || document.body == null) {
           document.write(launchTag);
           // go back to original page, otherwise current page becomes blank
           document.location = jnlpDocbase;
        } else {
           var divTag = document.createElement("div");
           divTag.id = "div1";
           divTag.style.position = "relative";
           divTag.style.left = "-10000px";
           divTag.style.margin = "0px auto";
           divTag.className ="dynamicDiv";
           divTag.innerHTML = launchTag;
           document.body.appendChild(divTag);
        }
   },

   createWebStartLaunchButtonEx: function(jnlp, minimumVersion) {

        if (this.returnPage == null) {
            // if there is an install, come back and run the jnlp file
            this.returnPage = jnlp;
        }

        var url = 'javascript:deployJava.launchWebStartApplication(\'' + jnlp +
			'\');';

        document.write('<' + 'a href="' + url +
                       '" onMouseOver="window.status=\'\'; ' +
                       'return true;"><' + 'img ' +
                       'src="' + this.launchButtonPNG + '" ' +
                       'border="0" /><' + '/' + 'a' + '>');
    },


    /**
     * Outputs a launch button for the specified JNLP URL.  When clicked, the
     * button will ensure that an appropriate JRE is installed and then launch
     * the JNLP application.  minimumVersion is of the form #[.#[.#[_#]]], and
     * is the minimum JRE version necessary to run this JNLP application.
     * minimumVersion is optional, and if it is not specified, '1.4.2'
     * will be used.
     * If an appropriate JRE or Web Start installation is detected,
     * the JNLP application will be launched, otherwise installLatestJRE()
     * will be called.
     *
     * After installLatestJRE() is called, the script will attempt to detect
     * that the JRE installation has completed and launch the JNLP application,
     * but there are circumstances (such as when the JRE installation
     * requires a browser restart) when this cannot be fulfilled.
     */
    createWebStartLaunchButton: function(jnlp, minimumVersion) {

        if (this.returnPage == null) {
            // if there is an install, come back and run the jnlp file
            this.returnPage = jnlp;
        }

        var url = 'javascript:' +
                  'if (!deployJava.isWebStartInstalled(&quot;' +
                      minimumVersion + '&quot;)) {' +
                      'if (deployJava.installLatestJRE()) {' +
                        'if (deployJava.launch(&quot;' + jnlp + '&quot;)) {}' +
                      '}' +
                  '} else {' +
                      'if (deployJava.launch(&quot;' + jnlp + '&quot;)) {}' +
                  '}';

        document.write('<' + 'a href="' + url +
                       '" onMouseOver="window.status=\'\'; ' +
                       'return true;"><' + 'img ' +
                       'src="' + this.launchButtonPNG + '" ' +
                       'border="0" /><' + '/' + 'a' + '>');
    },


    /**
     * Launch a JNLP application, (using the plugin if available)
     */
    launch: function(jnlp) {
   /*
    * Using the plugin to launch Java Web Start is disabled for the time being
    */
        document.location=jnlp;
        return true;
    },


    /*
     * returns true if the ActiveX or XPI plugin is installed
     */
    isPluginInstalled: function() {
        var plugin = this.getPlugin();
        if (plugin && plugin.jvms) {
            return true;
        } else {
            return false;
        }
    },

    /*
     * returns true if the plugin is installed and AutoUpdate is enabled
     */
    isAutoUpdateEnabled: function() {
        if (this.isPluginInstalled()) {
            return this.getPlugin().isAutoUpdateEnabled();
        }
        return false;
    },

    /*
     * sets AutoUpdate on if plugin is installed
     */
    setAutoUpdateEnabled: function() {
        if (this.isPluginInstalled()) {
            return this.getPlugin().setAutoUpdateEnabled();
        }
        return false;
    },

    /*
     * sets the preferred install type : null, online, kernel
     */
    setInstallerType: function(type) {
        this.installType = type;
        if (this.isPluginInstalled()) {
            return this.getPlugin().setInstallerType(type);
        }
        return false;
    },

    /*
     * sets additional package list - to be used by kernel installer
     */
    setAdditionalPackages: function(packageList) {
        if (this.isPluginInstalled()) {
            return this.getPlugin().setAdditionalPackages(
                                                     packageList);
        }
        return false;
    },

    /*
     * sets preference to install Early Access versions if available
     */
    setEarlyAccess: function(enabled) {
        this.EAInstallEnabled = enabled;
    },

    /*
     * Determines if the next generation plugin (Plugin II) is default
     */
    isPlugin2: function() {
        if (this.isPluginInstalled()) {
            if (this.versionCheck('1.6.0_10+')) {
                try {
                    return this.getPlugin().isPlugin2();
                } catch (err) {
                    // older plugin w/o isPlugin2() function -
                }
            }
        }
        return false;
    },

    //support native DT plugin?
    allowPlugin: function() {
        this.getBrowser();

        // Safari and Opera browsers find the plugin but it
        // doesn't work, so until we can get it to work - don't use it.
        var ret = ('Safari' != this.browserName2 &&
            'Opera' != this.browserName2);

        return ret;
    },

    getPlugin: function() {
        this.refresh();

        var ret = null;
        if (this.allowPlugin()) {
            ret = document.getElementById('deployJavaPlugin');
        }
        return ret;
    },

    compareVersionToPattern: function(version, patternArray,
                                      familyMatch, minMatch) {
        if (version == undefined || patternArray == undefined) {
           return false;
        }
        var regex = "^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$";
        var matchData = version.match(regex);

        if (matchData != null) {
            var index = 0;
            var result = new Array();

            for (var i = 1; i < matchData.length; ++i) {
                if ((typeof matchData[i] == 'string') && (matchData[i] != ''))
                {
                    result[index] = matchData[i];
                    index++;
                }
            }

            var l = Math.min(result.length, patternArray.length);

            // result contains what is installed in local machine
            // patternArray is what is being requested by application
            if (minMatch) {
                // minimum version match, return true if what we have (installed) 
                // is greater or equal to what is requested.  false otherwise. 
                for (var i = 0; i < l; ++i) {
                    if (result[i] < patternArray[i]) {
                        return false;
                    } else if (result[i] > patternArray[i]) {
                        return true;
                    }
                }
                return true;
            } else {
                for (var i = 0; i < l; ++i) {
                    if (result[i] != patternArray[i]) return false;
                }
                if (familyMatch) {
                    // family match - return true as long as what we have
                    // (installed) matches up to the request pattern
                    return true;
                } else { 
                    // exact match
                    // result and patternArray needs to have exact same content
                    return (result.length == patternArray.length);
                }
            }
        } else {
            return false;
        }
    },

    getBrowser: function() {

        if (this.browserName == null) {
            var browser = navigator.userAgent.toLowerCase();

            log('[getBrowser()] navigator.userAgent.toLowerCase() -> ' + browser);


            // order is important here.  Safari userAgent contains mozilla,
            // and Chrome userAgent contains both mozilla and safari.
            if ((browser.indexOf('msie') != -1) && (browser.indexOf('opera') == -1)) {
                this.browserName = 'MSIE';
                this.browserName2 = 'MSIE';
            } else if (browser.indexOf('iphone') != -1) {
                // this included both iPhone and iPad
                this.browserName = 'Netscape Family';
                this.browserName2 = 'iPhone';
            } else if ((browser.indexOf('firefox') != -1) && (browser.indexOf('opera') == -1)) {
                this.browserName = 'Netscape Family';
                this.browserName2 = 'Firefox';
            } else if (browser.indexOf('chrome') != -1) {
                this.browserName = 'Netscape Family';
                this.browserName2 = 'Chrome';
            } else if (browser.indexOf('safari') != -1) {
                this.browserName = 'Netscape Family';
                this.browserName2 = 'Safari';
            } else if ((browser.indexOf('mozilla') != -1) && (browser.indexOf('opera') == -1)) {
                this.browserName = 'Netscape Family';
                this.browserName2 = 'Other';
            } else if (browser.indexOf('opera') != -1) {
                this.browserName = 'Netscape Family';
                this.browserName2 = 'Opera';
            } else {
                this.browserName = '?';
                this.browserName2 = 'unknown';
            }

            log('[getBrowser()] Detected browser name:'+ this.browserName +
                       ', ' + this.browserName2);
        }
        return this.browserName;
    },


    testUsingActiveX: function(version) {
        var objectName = 'JavaWebStart.isInstalled.' + version + '.0';

        // we need the typeof check here for this to run on FF/Chrome
        // the check needs to be in place here - cannot even pass ActiveXObject
        // as arg to another function
        if (typeof ActiveXObject == 'undefined' || !ActiveXObject) {
            log('[testUsingActiveX()] Browser claims to be IE, but no ActiveXObject object?');
            return false;
        }

        try {
            return (new ActiveXObject(objectName) != null);
        } catch (exception) {
            return false;
        }
    },


    testForMSVM: function() {
        var clsid = '{08B0E5C0-4FCB-11CF-AAA5-00401C608500}';

        if (typeof oClientCaps != 'undefined') {
            var v = oClientCaps.getComponentVersion(clsid, "ComponentID");
            if ((v == '') || (v == '5,0,5000,0')) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    },


    testUsingMimeTypes: function(version) {
        if (!navigator.mimeTypes) {
            log ('[testUsingMimeTypes()] Browser claims to be Netscape family, but no mimeTypes[] array?');
            return false;
        }

        for (var i = 0; i < navigator.mimeTypes.length; ++i) {
            s = navigator.mimeTypes[i].type;
            var m = s.match(/^application\/x-java-applet\x3Bversion=(1\.8|1\.7|1\.6|1\.5|1\.4\.2)$/);
            if (m != null) {
                if (this.compareVersions(m[1], version)) {
                    return true;
                }
            }
        }
        return false;
    },

    testUsingPluginsArray: function(version) {
        if ((!navigator.plugins) || (!navigator.plugins.length)) {
            return false;
        }
        var platform = navigator.platform.toLowerCase();

        for (var i = 0; i < navigator.plugins.length; ++i) {
            s = navigator.plugins[i].description;
            if (s.search(/^Java Switchable Plug-in (Cocoa)/) != -1) {
                // Safari on MAC
                if (this.compareVersions("1.5.0", version)) {
                    return true;
                }
            } else if (s.search(/^Java/) != -1) {
                if (platform.indexOf('win') != -1) {
                    // still can't tell - opera, safari on windows
                    // return true for 1.5.0 and 1.6.0
                    if (this.compareVersions("1.5.0", version) ||
                        this.compareVersions("1.6.0", version)) {
                        return true;
                    }
                }
            }
        }
        // if above dosn't work on Apple or Windows, just allow 1.5.0
        if (this.compareVersions("1.5.0", version)) {
            return true;
        }
        return false;



    },

    IEInstall: function() {

        location.href = this.getJavaURL +
            ((this.returnPage != null) ?
            ('&returnPage=' + this.returnPage) : '') +
            ((this.locale != null) ?
            ('&locale=' + this.locale) : '') +
            ((this.brand != null) ? ('&brand=' + this.brand) : '');

         // should not actually get here
         return false;
    },

    done: function (name, result) {
    },

    FFInstall: function() {

        location.href = this.getJavaURL +
            ((this.returnPage != null) ?
            ('&returnPage=' + this.returnPage) : '') +
            ((this.locale != null) ?
            ('&locale=' + this.locale) : '') +
            ((this.brand != null) ? ('&brand=' + this.brand) : '') +
            ((this.installType != null) ?
                ('&type=' + this.installType) : '');

         // should not actually get here
         return false;
    },

    // return true if 'installed' (considered as a JRE version string) is
    // greater than or equal to 'required' (again, a JRE version string).
    compareVersions: function(installed, required) {

        var a = installed.split('.');
        var b = required.split('.');

        for (var i = 0; i < a.length; ++i) {
            a[i] = Number(a[i]);
        }
        for (var i = 0; i < b.length; ++i) {
            b[i] = Number(b[i]);
        }
        if (a.length == 2) {
            a[2] = 0;
        }

        if (a[0] > b[0]) return true;
        if (a[0] < b[0]) return false;

        if (a[1] > b[1]) return true;
        if (a[1] < b[1]) return false;

        if (a[2] > b[2]) return true;
        if (a[2] < b[2]) return false;

        return true;
    },

    enableAlerts: function() {
        // reset this so we can show the browser detection
        this.browserName = null;
        this.debug = true;
    },

    poll: function() {

        this.refresh();
        var postInstallJREList = this.getJREs();

        if ((this.preInstallJREList.length == 0) &&
            (postInstallJREList.length != 0)) {
            clearInterval(this.myInterval);
            if (this.returnPage != null) {
                location.href = this.returnPage;
            };
        }

        if ((this.preInstallJREList.length != 0) &&
            (postInstallJREList.length != 0) &&
            (this.preInstallJREList[0] != postInstallJREList[0])) {
            clearInterval(this.myInterval);
            if (this.returnPage != null) {
                location.href = this.returnPage;
            }
        }

    },

    writePluginTag: function() {
        var browser = this.getBrowser();

        if (browser == 'MSIE') {
            document.write('<' +
                'object classid="clsid:CAFEEFAC-DEC7-0000-0001-ABCDEFFEDCBA" ' +
                'id="deployJavaPlugin" width="0" height="0">' +
                '<' + '/' + 'object' + '>');
        } else if (browser == 'Netscape Family' && this.allowPlugin()) {
            this.writeEmbedTag();
        }
    },

    refresh: function() {
        navigator.plugins.refresh(false);

        var browser = this.getBrowser();
        if (browser == 'Netscape Family' && this.allowPlugin()) {
            var plugin = document.getElementById('deployJavaPlugin');
            // only do this again if no plugin
            if (plugin == null) {
                this.writeEmbedTag();
            }
        }
     },

    writeEmbedTag: function() {
        var written = false;
        if (navigator.mimeTypes != null) {
            for (var i=0; i < navigator.mimeTypes.length; i++) {
                if (navigator.mimeTypes[i].type == this.mimeType) {
                    if (navigator.mimeTypes[i].enabledPlugin) {
                        document.write('<' +
                            'embed id="deployJavaPlugin" type="' +
                            this.mimeType + '" hidden="true" />');
                        written = true;
                    }
                }
            }
            // if we ddn't find new mimeType, look for old mimeType
            if (!written) for (var i=0; i < navigator.mimeTypes.length; i++) {
                if (navigator.mimeTypes[i].type == this.oldMimeType) {
                    if (navigator.mimeTypes[i].enabledPlugin) {
                        document.write('<' +
                            'embed id="deployJavaPlugin" type="' +
                            this.oldMimeType + '" hidden="true" />');
                    }
                }
            }
        }
    }
    }; // deployJava object

    rv.writePluginTag();
    if (rv.locale == null) {
        var loc = null;

        if (loc == null) try {
            loc = navigator.userLanguage;
        } catch (err) { }

        if (loc == null) try {
            loc = navigator.systemLanguage;
        } catch (err) { }

        if (loc == null) try {
            loc = navigator.language;
        } catch (err) { }

        if (loc != null) {
            loc.replace("-","_")
            rv.locale = loc;
        }
    }

    return rv;
}();
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: fsa
  *	 Target: $f.IO
  *  Dependencies: 
  *		- $f
  *		- $f.IO
  *		- deployJava.debug.js (http://java.com/js/deployJava.js)
  * 	- fsa.jar (part of fluid framework) 
  *  Functionality:
  *		- this adds file system access via fsa.jar applet.
  *
  */
(function($f) { $f.extend.feature("fsa", "IO", "7efb99f8-a7c2-4d88-8f73-d3917a7984f8", function(self) {
	
	"use strict"; 
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "FileSystem access via fsa.jar",
		description: "Adds file system access capability using fsa.jar applet."
	};	
	
	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};
	
	// file system access
	this.fs = {
		// file system drivers
		drivers: {	
			// FileSystem Access (java applet driver of framework - needs Java runtime installed)
			fsa: {
				// driver id, name
				id: "fsa",
				name: "FileSystemApplet (fsa.jar)",
				
				// private functions 
				// not for public use
				// backward compatibility is not guranteed
				p: {
					javaUrlToFilename: function(url) {
						var f = "//localhost";
						var fileName = "";
						if (url.indexOf(f) === 0) {
							fileName = url.substring(f.length);
						} else {
							var i = url.indexOf(":");
							fileName = (i > 0 ? url.substring(i - 1) : url);
						};
						
						// return 
						return fileName;
					}
				},
				
				// checks if driver is available
				// returns (bool): true, if available, false otherwise
				isAvailable: function() {
					// return (check required version of JRE is installed, Java is enabled and fsa applet is available)
					return (deployJava.versionCheck($f.config.options.minJavaVersion) && 
							$f.env.browser.plugins.hasJava && 
							document.applets["fsa"]);
				},
				
				// creates given path
				// params:
				//	path (string): path to create
				// returns (boolean): true, if success, false, if failed					
				createPath: function(path) {
					// remove the filename, if present. 
					// use trailing slash (i.e. "foo\bar\") if no filename.
					path = self.fs.drivers.fsa.p.javaUrlToFilename(path);
					var pos = path.lastIndexOf("\\");
					if (pos !== -1) {
						path = path.substring(0, pos + 1);
					};
					
					// create path
					var isSuccess = false;
					try {
						isSuccess = document.applets["fsa"].createPath(path);
					} catch(ex) {
						$f.error("Error creating folder '" + path + "'.", false, false, ex);
					}
					
					// return
					return isSuccess;
				},

				// check if file exists
				// params:
				// 	completeFilePath (string): complete path of file
				// returns (boolean): true if found, false otherwise
				isFileExists: function(completeFilePath) {
					var isFound = false;
					try {
						// check
						isFound = document.applets["fsa"].exists(self.fs.drivers.fsa.p.javaUrlToFilename(completeFilePath), false);
					} catch (ex) {
						$f.error("Error finding file '" + completeFilePath + "'.", false, false, ex);
					};
					
					// return
					return isFound;				
				},

				// check if folder exists
				// params:
				// 	path (string): complete path of folder
				// returns (boolean): true if found, false otherwise					
				isFolderExists: function(path) {
					// remove the filename, if present. 
					// use trailing slash (i.e. "foo\bar\") if no filename.
					path = self.fs.drivers.fsa.p.javaUrlToFilename(path);
					var pos = path.lastIndexOf("\\");
					if(pos !== -1) {
						path = path.substring(0, pos + 1);
					};
					
					var isFound = false;
					try {
						// check
						isFound = document.applets["fsa"].exists(path, true);
					} catch(ex) {
						$f.error("Error finding path '" + path + "'.", false, false, ex);
					};
					
					// return
					return isFound;				
				},
				
				// read file content
				// params:
				// 	completeFilePath (string): complete path of file to read
				//	charset (string): chartset with which file is encoded  (empty means ASCII)
				// returns (string): null if error, string content otherwise
				readFile: function(completeFilePath, charset) {
					var encoding = "US-ASCII";
					// other possible options are
					// US-ASCII		Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
					// ISO-8859-1  	ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
					// UTF-8		Eight-bit UCS Transformation Format
					// UTF-16BE		Sixteen-bit UCS Transformation Format, big-endian byte order
					// UTF-16LE		Sixteen-bit UCS Transformation Format, little-endian byte order
					// UTF-16
					var content = null;
					var file = null;
					try {
						// get file
						file = document.applets["fsa"].readFile(self.fs.drivers.fsa.p.javaUrlToFilename(completeFilePath), charset);
						
						// read file
						if (!file) {
							content = null;
							$f.error("Error reading file '" + completeFilePath + "'. Error: File could not be loaded.", false, false);
						} else {
							content = String(file);
						};
					} catch(ex) {
						content = null;
						$f.error("Error reading file '" + completeFilePath + "'.", false, false, ex);
					};
					
					// return
					return content;
				},
				
				// write file content
				// params:
				// 	completeFilePath (string): complete path of file to write to
				//	charset (string): chartset with which file is to be encoded  (empty means ASCII)
				//	content (string): content to write to
				// returns (boolean): true if success, false if error
				writeFile: function(completeFilePath, charset, content) {
					var encoding = "US-ASCII";
					// other possible options are
					// US-ASCII		Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
					// ISO-8859-1  	ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
					// UTF-8		Eight-bit UCS Transformation Format
					// UTF-16BE		Sixteen-bit UCS Transformation Format, big-endian byte order
					// UTF-16LE		Sixteen-bit UCS Transformation Format, little-endian byte order
					// UTF-16
					var isSuccess = false;
					try {
						// try saving (this will create missing path on its own)
						var isSuccess = document.applets["fsa"].writeFile(self.fs.drivers.fsa.p.javaUrlToFilename(completeFilePath), charset, content);

					} catch (ex) {
						$f.error("Error writing file '" + completeFilePath + "'.", false, false, ex);							
					};
					
					// return
					return isSuccess;
				}				
			}	
		}
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: fileSystemObject driver
  *	 Target: $f.IO
  *  Dependencies: 
  *		- fluid core
  *		- fluid IO plugin
  *  Functionality:
  *		- this adds file system access via FileSystemObject activeX
  *
  */
(function($f) { $f.extend.feature("fileSystemObject", "IO", "77c5637a-f6a1-4509-bb52-16ac3e438417", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "FileSystem access via FSO",
		description: "Adds file system access capability using FileSystemObject ActiceX."
	};	
	
	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};
	
	// file system access
	this.fs = {
		// file system drivers
		drivers: {	
			// FileSystemObject driver
			fso: {
				// driver id, name
				id: "fso",
				name: "FileSystemObject (ActiveX)",
				
				// checks if driver is available
				// returns (bool): true, if available, false otherwise
				isAvailable: function() {
					var isFound = false;
					try {
						var fso = new ActiveXObject("Scripting.FileSystemObject");
						isFound = true;
					} catch (ex) {
						isFound = false;
					}
					
					// return
					return isFound;
				},

				// creates given path
				// params:
				//	path (string): path to create
				// returns (boolean): true, if success, false, if failed
				createPath: function(path) {
					// remove the filename, if present. 
					// use trailing slash (i.e. "foo\bar\") if no filename.
					var pos = path.lastIndexOf("\\");
					if (pos !== -1) {
						path = path.substring(0, pos + 1);
					};
					
					// walk up the path until we find a folder that exists
					var isSuccess = false;
					var scan = [path];
					try {
						// create object
						var fso = new ActiveXObject("Scripting.FileSystemObject");
						
						// walk
						var parent = fso.GetParentFolderName(path);
						while (parent && !fso.FolderExists(parent)) {
							scan.push(parent);
							parent = fso.GetParentFolderName(parent);
						};
						
						// walk back down the path, creating folders
						for (i = scan.length - 1; i >= 0; i--) {
							if (!fso.FolderExists(scan[i])) {
								fso.CreateFolder(scan[i]);
							};
						};
						
						// set
						isSuccess = true;
					} catch (ex) {
						$f.error("Error creating folder '" + path + "'.", false, false, ex);
					};
					
					// return
					return isSuccess;
				},				
				
				// check if file exists
				// params:
				// 	completeFilePath (string): complete path of file
				// returns (boolean): true if found, false otherwise
				isFileExists: function(completeFilePath) {
					var isFound = false;
					try {
						// create object
						var fso = new ActiveXObject("Scripting.FileSystemObject");
						
						// check
						isFound = fso.FileExists(completeFilePath);
					} catch (ex) {
						$f.error("Error finding file '" + completeFilePath + "'.", false, false, ex);
					};
					
					// return
					return isFound;				
				},
				
				// check if folder exists
				// params:
				// 	path (string): complete path of folder
				// returns (boolean): true if found, false otherwise					
				isFolderExists: function(path) {
					// check
					var isFound = false;
					try {
						// create object
						var fso = new ActiveXObject("Scripting.FileSystemObject");
						
						// check
						isFound = fso.FolderExists(path);
					} catch (ex) {
						$f.error("Error finding folder '" + path + "'.", false, false, ex);
					}
					
					// return
					return isFound;	
				},
				
				// read file content
				// params:
				// 	completeFilePath (string): complete path of file to read
				//	charset (string): chartset with which file is encoded  (empty means ASCII)
				// returns (string): null if error, string content otherwise
				readFile: function(completeFilePath, charset) {
					var content = null;
					var file = null;
					try {
						// create object
						var fso = new ActiveXObject("Scripting.FileSystemObject");
						
						// open file
						var mode = 1; // for reading
						var isCreate = false;
						var format = 0; // ascii
						if (charset) {
							format = -1; // unicode (LIMITATION being that FSO can understand only UTF-16LE form of unicode)
						};
						file = fso.OpenTextFile(completeFilePath, mode, isCreate, format); 
						
						// read file
						content = file.ReadAll();
					} catch(ex) {
						content = null;
						$f.error("Error reading file '" + completeFilePath + "'.", false, false, ex);
					} finally {
						// close file
						if (!isNull(file)) {
							file.Close();
						};
					};
					
					// return
					return content;
				},
				
				// write file content
				// params:
				// 	completeFilePath (string): complete path of file to write to
				//	charset (string): chartset with which file is to be encoded  (empty means ASCII)
				//	content (string): content to write to
				// returns (boolean): true if success, false if error
				writeFile: function(completeFilePath, charset, content) {
					var isSuccess = false;
					try {
						// save if path is available
						if (self.fs.drivers.fso.createPath(completeFilePath)) {
							// create object
							var fso = new ActiveXObject("Scripting.FileSystemObject");
							
							// open file
							var mode = 2; // for writing
							var isCreate = true;
							var format = 0; // ascii
							if (charset) {
								format = -1; // unicode (LIMITATION being that FSO can understand only UTF-16LE form of unicode)
							};								
							var file = fso.OpenTextFile(completeFilePath, mode, isCreate, format); 
							
							// write
							file.Write(content);
							
							// set
							isSuccess = true;
						};
					} catch (ex) {
						$f.error("Error writing file '" + completeFilePath + "'.", false, false, ex);							
					} finally {
						// close file
						if (!isNull(file)) {
							file.Close();
						};							
					};
					
					// return
					return isSuccess;
				}				
			}		
		}
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: IO
  *  Dependencies: 
  *		- $f
  *		- $f.environment
  *  Functionality:
  *		- It provides core file read/write operations in various scenarios.
  *     - Does not process other plugins.
  *
  */
(function($f) { $f.extend.system("IO", "2bb45039-f381-4e4c-b774-0fb1f068fb91", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// data root
	var getDataRoot = function() {
		// call here should never come if local file system access is not enabled
		// if it is coming that's a problem call (log it)
		if (!$f.config.options.isEnableLocalFileSystemAccess) {
			$f.error("Local file system access is not available. %DATA% cannot be resolved.", false, false);
		};
	
		// return 
		return $f.env.dataRoot();
	};
	
	// temp root
	var getTempRoot = function() {
		var tempRoot = $f.config.options.tempFolder;
		if (isEmpty(tempRoot)) {
			tempRoot = "temp"; // inbuilt default
		};
		// always inside data folder
		tempRoot = getDataRoot() + "/" + tempRoot;
		
		// return 
		return tempRoot;
	};
	
	// fluid root
	var getFluidRoot = function() {
		var fluidRoot = $f.config.options.fluidFolder;
		if (isEmpty(fluidRoot)) {
			fluidRoot = "fluid"; // inbuilt default
		};	
		
		// return 
		return fluidRoot;
	};		

	// app root
	var getAppRoot = function() {
		var appRoot = $f.config.options.appFolder;
		if (isEmpty(appRoot)) {
			appRoot = "app"; // inbuilt default
		};	
		
		// return 
		return appRoot;
	};				
	
	// resource root
	var getResRoot = function() {
		var resRoot = $f.config.options.resourcesFolder;
		if (isEmpty(resRoot)) {
			// always inside app folder
			resRoot = getAppRoot() + "/res"; // inbuild default
		};
		var currentLocale = ""; 
		if ($f.i18n) {
			currentLocale = $f.i18n.currentLocale().locale;
		};
		if (!currentLocale) {
			currentLocale = "en-US"; // inbuilt default
		};	
		resRoot = resRoot + "/" + currentLocale;
		
		// return 
		return resRoot;
	};			
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "IO",
		description: "Provides consistent IO operations in various scenarios."
	};
		
	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// try and access file system driver
		// this will add required applet, if not added
		if ($f.config.options.isEnableLocalFileSystemAccess) {
			// get driver
			var driver = self.fs.get();
			
			// if need java, go and download Java first
			if (driver.id === self.fs.drivers.needJava.id) {                 
				$f.alert("This application requires latest version of Java Runtime Environment (JRE). " + 
						 "You would now be redirected to install/enable it now before you continue running this application.");
				window.location = $f.config.options.javaInstallerUrl;
				throw "Cannot run without Java runtime environment"; // this will break execution
			};
		} else {
			$f.trace("file system access is disabled.");
		};			

		// can we process file includes
		var canProcessFileInclude = $f.document.has.feature("fileInclude");
		
		// include all files of framework and all plugins which are supposed to load before IO
		// this is a special call because unless IO loads, files cannot be loaded and since
		// $f and some plugins are loaded before IO, IO is taking care of loading libs of $f and other plugins
		// for every other plugin libs are loaded when plugin is loaded
		var pendingIncludeFilesQueue = $f.p.getPendingIncludeFilesQueue();
		if (isArray(pendingIncludeFilesQueue)) {
			// include files for framework in queue
			if (canProcessFileInclude) {
				$f.document.includeFiles($f); // (this will end-up in plugin.handle.onIncludeComplete())
			} else {
				// directly send it for completion, since includes cannot be processed
				$f.handle.onIncludeComplete();
			};
			
			// include files for plugins in queue
			$.each(pendingIncludeFilesQueue, function(i, plugin) {
				if (canProcessFileInclude) {
					$f.document.includeFiles(plugin); // (this will end-up in plugin.handle.onIncludeComplete())
				} else {
					// directly send it for completion, since includes cannot be processed
					plugin.handle.onIncludeComplete();
				};
			});
		};

		// include all files of all features which are supposed to load before IO
		// this is a special call because unless IO loads, files cannot be loaded and since
		// some features are loaded before IO, IO is taking care of loading libs of these features
		// for every other feature libs are loaded when feature is loaded
		var pendingFeatureIncludeFilesQueue = $f.p.getPendingFeatureIncludeFilesQueue();
		if (isArray(pendingFeatureIncludeFilesQueue)) {
			// include files for features in queue
			$.each(pendingFeatureIncludeFilesQueue, function(i, extenderInstance) {
				if (canProcessFileInclude) {
					$f.document.includeFeatureFiles(extenderInstance); // (this will end-up in extenderInstance.featureHandle.onFeatureIncludeComplete())
				} else {
					// directly send for completion, includes can not to be processed
					extenderInstance.featureHandle.onFeatureIncludeComplete();
				};
			});
		};

		// return
		return true; 
	};
		
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// current file system driver
		currentFSDriver: null
	};
		
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 125				
	};
		
	// folder operations
	this.folder = {
		// convert url to local path
		// params:
		//	url (string): url to convert to local file system path
		// returns (string): local file system path 
		urlToLocal: function(url) {
			// return
			return $f.env.p.urlToLocalPath(url);
		},
	
		// get path from complete file path
		// params:
		//	completeFilePath (string): complete file path
		// returns (string): only path without file name 
		onlyPath: function(completeFilePath) {
			// find last "\" or "/"
			var lastPlace = -1;
			if ($f.deploymentMode.isPortable()) {
				// if portable version
				lastPlace = completeFilePath.lastIndexOf("\\");
			} else if ($f.deploymentMode.isWrapped()) {
				// TODO: Handle wrappedApp case
			} else {
				// any other online version
				lastPlace = completeFilePath.lastIndexOf("/");
			};
			
			// get only path
			var onlyPath = completeFilePath;
			if 	(lastPlace !== -1) {
				onlyPath = completeFilePath.substring(0, lastPlace);
			};
			
			// return
			return onlyPath;
		},

		// adds root path to given partial path and resolve placeholders in partial path
		// params:
		//	partialFilePath (string): partial file path that needs to be prefixed with root path 
		//							  partial file path may contain special place holders in the
		//						      beginning for special path values such as:
		//							  %APP%, %DATA%, %TEMP%, %RES%, %FLUID%
		// returns (string): returns complete file path
		getCompletePath: function(partialFilePath) {
			// create complete path
			var completePath = "";
			if (partialFilePath) {
				if ($f.deploymentMode.isPortable()) {
					// if portable version
					// add initial "\" if not added
					if (partialFilePath.charAt(0) !== "\\") { 
						partialFilePath = "\\" + partialFilePath;
					};
				} else if ($f.deploymentMode.isWrapped()) {
					// TODO: Handle wrappedApp case
				} else {
					// any other online version
					// add initial "/" if not added (only if this is not %DATA% path
					if (partialFilePath.charAt(0) !== "/" && 
						partialFilePath.toLowerCase().indexOf("%data%") !== 0 &&
						partialFilePath.toLowerCase().indexOf("%temp%") !== 0) { 
						partialFilePath = "/" + partialFilePath;
					};
				};					
				
				if (!$f.deploymentMode.isPortable() && 
					(partialFilePath.toLowerCase().indexOf("%data%") === 0 ||
					 partialFilePath.toLowerCase().indexOf("%temp%") === 0)) {
					// any online version and path is a %DATA% path (%TEMP% goes inside %DATA%)
					// resolve placeholders
					completePath = self.folder.getResolvedPath(partialFilePath);
					
					// no need to add root, because in this case root is already added in dataroot folder
				} else {
					// any online version and path is NOT %DATA% path OR portable version
					// resolve placeholders if any
					partialFilePath = self.folder.getResolvedPath(partialFilePath);
					
					// get complete path
					completePath = $f.env.root() + partialFilePath;
				};
			};

			// return
			return completePath;
		},			
		
		// resolve placeholders in partial path
		// params:
		//	partialFilePath (string): partial file path that needs to resolved for special place holders in the
		//						      beginning for special path values such as:
		//							  %APP%, %DATA%, %TEMP%, %RES%, %FLUID%
		//	asWebPath (boolean): Optional. if return as web path and don't change / to \
		// returns (string): returns resolved partial file path
		getResolvedPath: function(partialFilePath, asWebPath) { 
			if (!isDefined(asWebPath)) {
				asWebPath = false;
			};
			
			// replace placeholders (%APP%, %DATA%, %TEMP%, %RES%, %FLUID%) in partialFilePath
			var isDataPath = false;
			if (partialFilePath.indexOf("%DATA%") !== -1) {
				isDataPath = true;
				partialFilePath = partialFilePath.replace("%DATA%", getDataRoot());
			}; 
			if (partialFilePath.indexOf("%TEMP%") !== -1) {
				isDataPath = true; // because %TEMP% is always in %DATA%
				partialFilePath = partialFilePath.replace("%TEMP%", getTempRoot());
			}; 
			if (partialFilePath.indexOf("%FLUID%") !== -1) {
				partialFilePath = partialFilePath.replace("%FLUID%", getFluidRoot());
			}; 
			if (partialFilePath.indexOf("%RES%") !== -1) {
				partialFilePath = partialFilePath.replace("%RES%", getResRoot());
			};
			if (partialFilePath.indexOf("%APP%") !== -1) {
				partialFilePath = partialFilePath.replace("%APP%", getAppRoot());
			};
			
			if (!asWebPath) {
				if ($f.deploymentMode.isPortable() || isDataPath) {
					// if portable version
					// replace all "/" with "\"
					partialFilePath = partialFilePath.replace(/\//g, "\\");				
				} else {
					// any other online version
					// replace all "\" with "/"
					partialFilePath = partialFilePath.replace(/\\/g, "/");					
				};
			} else {
				// replace all "\" with "/"
				partialFilePath = partialFilePath.replace(/\\/g, "/");					
			};
			
			// return
			return partialFilePath;
		}			
	};
		
	// file system access
	this.fs = {
		// get available file system driver
		// returns (object): file system driver object
		get: function() {
			var driver = self.vars.currentFSDriver;
			if (isNull(driver)) {
				if ($f.config.options.isEnableLocalFileSystemAccess) {
					var drvList = self.fs.drivers.list();
					if (drvList.length === 0) {
						// since list is empty, we definitely need jave plugin to run
						driver = self.fs.drivers.needJava;
					} else {
						$.each(drvList, function(i, drv) {
							if (self.fs.drivers[drv].isAvailable()) {
								driver = self.fs.drivers[drv];
								return false; // break
							};
						});
					};
				} else {
					driver = self.fs.drivers.fake;
				};
				
				// inform, if required
				if (isNull(driver)) {
					$f.error("Unable to get file system driver.", false, false);
					// since no driver is found, we definitely need jave plugin for the browser
					// to run
					driver = self.fs.drivers.needJava;						
				};
				
				// set for next use
				self.vars.currentFSDriver = driver;
				
				// add to trace
				$f.trace("Chosen file system driver: ---> " + driver.name + " <---");
			};
			
			// return
			return driver;
		},
		
		// file system drivers
		drivers: {
			// list of available drivers in preferred order of access
			// based on current browser and environment
			// returns (array): ordered list of drivers
			list: function() {
				// use user defined order if defined
				var orderedList = [];
				if ($f.config.options.fileSystemDriversCustomOrder.length !== 0) {
					orderedList = $f.config.options.fileSystemDriversCustomOrder.split(",");
				} else {
					// build preferential order
					if (self.fs.drivers.fsa) {
						orderedList.push("fsa");
					};
					if (self.fs.drivers.fso) {
						orderedList.push("fso");
					};
				};
			
				// add any other available drivers added via some feature
				var ignoreNames = "'list', 'needJava', 'fake', "
				$.each(orderedList, function(i, name) {
					ignoreNames += "'" + name + "', ";
				});				
				$.each(self.fs.drivers, function(name, value) {
					if (ignoreNames.indexOf("'" + name + "'") === -1) {
						orderedList.push(name); // these are in no specific order 
					};
				});

				// return
				return orderedList;
			},
			
			// fake driver for scenario when no relevant driver found and installing java is a must
			needJava: {
				// driver id, name
				id: "needJava",
				name: "Need Java (Cannot function properly without Java plugin.)",

				// checks if driver is available
				// returns (bool): true, if available, false otherwise
				isAvailable: function() {
					// return
					return true;
				},
				
				// creates given path
				// params:
				//	path (string): path to create
				// returns (boolean): true, if success, false, if failed					
				createPath: function(path) {
					// prompt user to install java
					$f.env.loadJavaIfRequired();

					// log this scenario, ideally no call should come here
					$f.error("Attempt to create path  '" + path + "' when no valid local file driver is available. Install Java plugin.", false, false);
					
					// return
					return false;					
				},
				
				// check if file exists
				// params:
				// 	completeFilePath (string): complete path of file
				// returns (boolean): true if found, false otherwise
				isFileExists: function(completeFilePath) {
					// prompt user to install java
					$f.env.loadJavaIfRequired();

					// log this scenario, ideally no call should come here
					$f.error("Attempt to check existence of file '" + completeFilePath + "' when no valid local file driver is available. Install Java plugin.", false, false);
					
					// return
					return false;
				},
				
				// check if folder exists
				// params:
				// 	path (string): complete path of folder
				// returns (boolean): true if found, false otherwise					
				isFolderExists: function(path) {
					// prompt user to install java
					$f.env.loadJavaIfRequired();

					// log this scenario, ideally no call should come here
					$f.error("Attempt to check existence of folder '" + path + "' when no valid local file driver is available. Install Java plugin.", false, false);
					
					// return
					return false;					
				},
				
				// read file content
				// params:
				// 	completeFilePath (string): complete path of file to read
				//	charset (string): chartset with which file is encoded  (empty means ASCII)
				// returns (string): null if error, string content otherwise
				readFile: function(completeFilePath, charset) {
					// prompt user to install java
					$f.env.loadJavaIfRequired();
					
					// log this scenario, ideally no call should come here
					$f.error("Attempt to read file '" + completeFilePath + "' when no valid local file driver is available. Install Java plugin.", false, false);
					
					// return
					return null;
				},
				
				// write file content
				// params:
				// 	completeFilePath (string): complete path of file to write to
				//	charset (string): chartset with which file is to be encoded  (empty means ASCII)
				//	content (string): content to write to
				// returns (boolean): true if success, false if error
				writeFile: function(completeFilePath, charset, content) {				
					// prompt user to install java
					$f.env.loadJavaIfRequired();

					// log this scenario, ideally no call should come here
					$f.error("Attempt to write file '" + completeFilePath + "' when no valid local file driver is available. Install Java plugin.", false, false);
					
					// return
					return false;
				}					
			},
			
			// fake driver for scenario when local file system access is disabled
			fake: {
				// driver id, name
				id: "fake",
				name: "Fake (Local file system access is disabled.)",

				// checks if driver is available
				// returns (bool): true, if available, false otherwise
				isAvailable: function() {
					// return
					return true;
				},
				
				// creates given path
				// params:
				//	path (string): path to create
				// returns (boolean): true, if success, false, if failed					
				createPath: function(path) {
					// log this scenario, ideally no call should come here
					$f.error("Attempt to create path  '" + path + "' when local file system access is disabled.", false, false);
					
					// return
					return false;					
				},
				
				// check if file exists
				// params:
				// 	completeFilePath (string): complete path of file
				// returns (boolean): true if found, false otherwise
				isFileExists: function(completeFilePath) {
					// log this scenario, ideally no call should come here
					$f.error("Attempt to check existence of file '" + completeFilePath + "' when local file system access is disabled.", false, false);
					
					// return
					return false;
				},

				// check if folder exists
				// params:
				// 	path (string): complete path of folder
				// returns (boolean): true if found, false otherwise					
				isFolderExists: function(path) {
					// log this scenario, ideally no call should come here
					$f.error("Attempt to check existence of folder '" + path + "' when local file system access is disabled.", false, false);
					
					// return
					return false;					
				},
				
				// read file content
				// params:
				// 	completeFilePath (string): complete path of file to read
				//	charset (string): chartset with which file is encoded  (empty means ASCII)
				// returns (string): null if error, string content otherwise
				readFile: function(completeFilePath, charset) {
					// log this scenario, ideally no call should come here
					$f.error("Attempt to read file '" + completeFilePath + "' when local file system access is disabled.", false, false);
					
					// return
					return null;
				},

				// write file content
				// params:
				// 	completeFilePath (string): complete path of file to write to
				//	charset (string): chartset with which file is to be encoded  (empty means ASCII)
				//	content (string): content to write to
				// returns (boolean): true if success, false if error
				writeFile: function(completeFilePath, charset, content) {				
					// log this scenario, ideally no call should come here
					$f.error("Attempt to write file '" + completeFilePath + "' when local file system access is disabled.", false, false);
					
					// return
					return false;
				}				
			}
		}
	};
		
	// file operations
	this.file = {
		// checks if given file exists locally
		// params:
		//	completeFilePath (string): complete file path of file to be checked 
		// returns (boolean): 
		//	true: if file exists
		//	false: otherwise		
		isExistsLocally: function(completeFilePath) {
			// find as per deployment mode
			var found = false;
			if ($f.deploymentMode.isPortable()) {
				// if portable version
				found = self.fs.get().isFileExists(completeFilePath);
			} else if ($f.deploymentMode.isWrapped()) {
				// TODO: Handle wrappedApp case
			} else {
				// any other online version
				// for paths which are %DATA% paths, do perform local check
				var dataRoot = $f.vars._currentDataRoot.toLowerCase();
				if (completeFilePath.toLowerCase().indexOf(dataRoot) === 0) {
					found = self.fs.get().isFileExists(completeFilePath);
				} else {
					found = true; // always true for a local check in this case
				};
			};
		
			// return
			return found;
		},
		
		// read content of file
		// params:
		//	completeFilePath (string): complete file path that is to be read from local file system
		//	charset (string): chartset with which file is encoded  (empty means ASCII)
		// returns (string): returns the content of the file, if success, empty if error
		read: function(completeFilePath, charset) {
			var fileContent = "";
			if (self.file.isExistsLocally(completeFilePath)) {
				try {
					fileContent = self.fs.get().readFile(completeFilePath, charset);
					if (!isString(fileContent)) {
						fileContent = "";
					};
				} catch (ex) {
					$f.error("Failed to read from file '" + completeFilePath + "'.", false, false, ex);
					fileContent = "";
				};
			} else {
				$f.error("File '" + completeFilePath + "' not found.", false, false);
			};
			
			// return
			return fileContent;
		},
		
		// write content to file
		// params:
		//	completeFilePath (string): complete file path that is to be written to into local file system
		//	charset (string): chartset with which file is to be encoded  (empty means ASCII)
		//	fileContent (string): file content that is to be written
		// returns (boolean): 
		//	true: if success
		//	false: if failed
		write: function(completeFilePath, charset, fileContent) {
			var success = false;
			try {
				success = self.fs.get().writeFile(completeFilePath, charset, fileContent);
			} catch (ex) {
				$f.error("Failed to write to file '" + completeFilePath + "'.", false, false, ex);
				success = false;
			};
			
			// return
			return success;
		},	

		// reads specified file async (locally or from server) and returns file content
		// params: 
		//	file (string): name of the file that is to read (can have placeholders in it)
		//  charset (string): chartset with which file is encoded  (empty means ASCII)
		//  data (object): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after file is loaded
		//						 signature of this function should be: void callBackFunc(data, isError);			
		// returns (void):
		readASync: function(file, charset, data, callback) {
			if (file) {
				// load as per deployment mode
				if ($f.deploymentMode.isPortable() || $f.deploymentMode.isWrapped()) {
					// load async
					$.doTimeout($f.utils.guid(), 1, function() {
						// file to read
						var fileToRead = self.folder.getCompletePath(file);
						
						// read
						var fileContent = self.file.read(fileToRead, charset);

						// callback
						if (isFunction(callback)) {
							callback(data, fileContent, isEmpty(fileContent));
						};					

						// done
						return false; // so it does not poll
					});								
				} else {
					// any other online version
					var fileToRead = self.folder.getResolvedPath(file);

					// get file string 
					var onFileAJAXCallComplete = function(fileContent, isError) {
						// callback
						if (isFunction(callback)) {
							callback(data, fileContent, isError);
						};
					};
					
					var contentType = "application/text";
					if (charset) {
						contentType = "application/text; charset=" + charset.toLowerCase();
					};
					$.ajax(fileToRead, {
						dataType: "text",
						contentType: contentType,
						error: function(jqXHR, textStatus, errorThrown) { 
							// log error
							$f.error("Error loading file '" + file + "'. Status: '" + textStatus + "'.", false, false, errorThrown);
							
							// callback irrecpective
							onFileAJAXCallComplete("", true);
						},
						success: function(fileContent, textStatus, jqXHR) {
							// callback
							onFileAJAXCallComplete(fileContent, false);
						}
					});					
				};
			} else {
				// log error
				$f.error("Error loading file. File name not specified.", false, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, "", true);
				};				
			};
		},
			
		// writes specified file content async (locally or to server)
		// params: 
		//	file (string): name of the file that is to br written to (can have placeholders in it)
		//  charset (string): chartset with which file is encoded  (empty means ASCII)
		//	fileContent (string): file content that is to be written
		//  data (object): data that is to be passed back to callback function
		//  callback (function): callback function that will be called after file is written
		//						 signature of this function should be: void callBackFunc(data, isError);			
		// returns (void):
		writeASync: function(file, charset, fileContent, data, callback) {
			if (file) {
				if ($f.deploymentMode.isPortable() || $f.deploymentMode.isWrapped()) {
					// write async
					$.doTimeout($f.utils.guid(), 1, function() {
						// file to write
						var fileToWrite = self.folder.getCompletePath(file);
						
						// write
						var success = self.file.write(fileToWrite, charset, fileContent);

						// callback
						if (isFunction(callback)) {
							callback(data, !success);
						};					

						// done
						return false; // so it does not poll
					});								
				} else {
					// any other online version
					// pass it to app to handle 
					if ($f.app && isFunction($f.app.onWriteToServerRequest)) {
						$f.app.onWriteToServerRequest(file, charset, fileContent, data, callback);
					} else {
						// callback w error
						if (isFunction(callback)) {
							$f.error("Cannot write to server. Not supported.", true, false);
							callback(data, true);
						};
					};
				};
			} else {
				// log error
				$f.error("Error writing file. File name not specified.", false, false);
				
				// callback
				if (isFunction(callback)) {
					callback(data, true);
				};				
			};
		}			
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: sessionStore
  *  Dependencies: 
  * 	- fluid core
  *  Functionality:
  *		- this plugin provides client-side session storage capabilities.
  *		- it does process other plugins for following property, if defined
  *			> session
  *
  */
(function($f) { $f.extend.system("sessionStore", "sess", "5866458f-02fd-43d9-aebe-2b2c8597de81", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// fluid session item
	// params: 
	//	pluginId (string): id of the plugin for which this session item is
	//	name (string): name of the session item
	//	defaultValue (object): default value of the session item (must be JSON serializable)
	// returns (object): returns new instance of configured fluid session item
	var fluidSession = function(pluginId, name, defaultValue) {
		// plugin id
		this.pluginId = pluginId;
		
		// session item name
		this.name = name;

		// default value
		this.defaultValue = defaultValue;
		
		// get session item value from session
		// returns (object): session item value value if found, else default value
		this.get = function() {
			// get default value
			var value = this.defaultValue;
			
			// try to locate value in session
			var stringValue = self.get(this.pluginId + "_" + this.name, null);
			if (!isNull(stringValue)) {
				value = JSON.parse(stringValue);
			};
			
			// return
			return value;
		};
		
		// set session item value into session
		// params:
		//	value (object): value to be saved (must be JSON serializable) or Null, if this is to be removed
		// returns (void):
		this.set = function(value) {
			// set default value (if not defined)
			if (isNull(value)) {
				value = this.defaultValue;
			};
			
			// stringify, if required
			if (!isNull(value)) {
				value = JSON.stringify(value);
			};
			
			// set value in session
			self.set(this.pluginId + "_" + this.name, value);
		};
		
		// initialize if not already done
		// returns (object): self instance
		this.init = function() {
			// store default value in session, if not already stored
			var stringValue = self.get(this.pluginId + "_" + this.name, null);
			if (isNull(stringValue)) {
				this.set(this.defaultValue);
			};		
			
			// return
			return this;
		};
	};		
		
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

	// plugin info
	this.info = {
		title: "Session Store",
		description: "Provides client-side session storage capabilities."
	};
	
	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// set if session is new
		if (self.has(self.config.startedAtSessionKey)) {
			self.vars.isNew = false;
			self.vars.startedAt = new Date(self.get(self.config.startedAtSessionKey, ""));
		} else {
			self.vars.isNew = true;
			self.vars.startedAt = new Date();
			self.set(self.config.startedAtSessionKey, self.startedAt.get().toString());
		};	
		
		// return
		return true; 
	};
	
	// reset handler
	// returns: (void)
	this.onReset = function() {
		// clear self 
		self.clear();
	};
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = { 
		// if session is a new session
		isNew: true,
		
		// date and time when session was started first time
		startedAt: new Date()
	};
	
	// plugin configuration
	this.config = {
		// key using which session started date and time is stored in session
		startedAtSessionKey: "_sessionStartedAt",
		
		// session items fixed prefix
		// used by all keys as prefix 
		// this is done to identify the keys in session which are 
		// added by this plugin
		sessionStorePrefix: "_sessionStore_",

		// can this plugin configure other plugins
		// if this is set to true, after plugins are initialized, these will be
		// given to this plugin's configure method to do required configuration
		canConfigurePlugins: true,

		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 225					
	};			

	// configure given plugin 
	// this is called for each plugin if canConfigurePlugins is set to true
	// params:
	//	plugin (object): plugin object to configure
	//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
	//                                        this plugin otherwise should also be done now with
	//                                        this plugin, because this is being loaded after all
	//                                        batch processing is done at load time
	//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
	// 										    a new feature is added to plugin which may have added
	//											some members those required reconfiguration	
	// returns (void):	
	this.configure = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {
		// confugure session items for given plugin
		if (plugin && plugin.session) {
			$.each(plugin.session, function(name, defaultValue) {
				// create and assign session item instance, if not already created
				if (!isNull(defaultValue) && !(plugin.session[name] instanceof fluidSession)) {
					plugin.session[name] = new fluidSession(plugin.handle.id, name, defaultValue).init();
				};
			});
		};		
	};

	// represents if session is a new session
	this.isNew = $f.utils.object.factory.getNew.varProperty(self, "isNew");
	
	// date and time when session was started first time
	this.startedAt = $f.utils.object.factory.getNew.varProperty(self, "startedAt");
	
	// get value of the item as stored in session
	// params:
	//	key (string): key of the session item
	//	defaultValue (string): value to return if key not found in session
	//	isExternal (bool): if this should be treated as an external item
	// returns (string): value from the session if found, defaultValue otherwise
	this.get = function(key, defaultValue, isExternal) { 
		// default value
		var value = defaultValue;
		
		// read either from window.sessionStorage or from window.name
		if (key) {
			// update key with prefix (if not an external item)
			if (!isExternal) {
				key = self.config.sessionStorePrefix + key;
			};
				
			if (window.sessionStorage) {
				// get value
				value = window.sessionStorage.getItem(key);
				if (!value) {
					value = defaultValue;
				};
			} else {
				if (!isEmpty(window.name)) {
					var sessionData = JSON.parse(window.name);
					$.each(sessionData, function(index, item) {
						if (item.k === key) {
							value = item.v;
							return false; // break
						};
					});
				};
			};
		};
		
		// return
		return value; 
	};
	
	// set value of the item in session
	// params:
	//	key (string): key of the session item
	//	value (string): value to save or Null, if item is to be removed
	//	isExternal (bool): if this should be treated as an external item
	// returns (void): 
	this.set = function(key, value, isExternal) { 
		// write either to window.sessionStorage or to window.name
		if (key) {
			// update key with prefix (if not an external item)
			if (!isExternal) {
				key = self.config.sessionStorePrefix + key;
			};	

			if (window.sessionStorage) {
				if (!isNull(value)) {
					window.sessionStorage.setItem(key, value);
				} else {
					window.sessionStorage.removeItem(key);
				};
			} else {
				var sessionData = [];
				if (!isEmpty(window.name)) {
					sessionData = JSON.parse(window.name);
					var idx = -1;
					$.each(sessionData, function(index, item) {
						if (item.k === key) {
							idx = index;
							return false; // break
						};
					});
					if (idx !== -1) {
						sessionData.splice(idx, 1); // remove old
					};
				};
				// add only if it was not null (because it is already removed anyways)
				if (!isNull(value)) {
					sessionData.push({k:key, v:value}); // add new one
				};
				window.name = JSON.stringify(sessionData);
			};
		};
	};
	
	// number of items that are currently stored in session
	// returns (number): count of items in session
	//				     Note: external items are not counted
	this.count = function() {
		// read either window.sessionStorage or window.name
		var length = 0;
		if (window.sessionStorage) {
			$.each(window.sessionStorage, function(name, value) {
				// add 
				if (name.indexOf(self.config.sessionStorePrefix) === 0) {
					length++;
				};
			});
		} else {
			var sessionData = [];
			if (!isEmpty(window.name)) {
				sessionData = JSON.parse(window.name);
			};
			$.each(sessionData, function(i, item) {
				// add 
				if (item.k.indexOf(self.config.sessionStorePrefix) === 0) {
					length++;
				};
			});
		};
		
		// return
		return length;
	};

	// item names array that are currently stored in session
	// returns (array): array of item names that are stored in session
	//				    Note: external items are not included
	this.items = function() {
		// read either window.sessionStorage or window.name
		var sessionItems = [];
		if (window.sessionStorage) {
			$.each(window.sessionStorage, function(name, value) {
				// add after removing prefix from this name if this was stored by this plugin
				if (name.indexOf(self.config.sessionStorePrefix) === 0) {
					sessionItems.push(name.substring(self.config.sessionStorePrefix.length));
				};
			});
		} else {
			if (!isEmpty(window.name)) {
				sessionData = JSON.parse(window.name);
				$.each(sessionData, function(index, item) {
					// add after removing prefix from this name if this was stored by this plugin
					if (item.k.indexOf(self.config.sessionStorePrefix) === 0) {
						sessionItems.push(item.k.substring(self.config.sessionStorePrefix.length));
					};
				});
			};
		};
		
		// return
		return sessionItems;
	};
	
	// check if specified key exists in session
	// params:
	//	key (string): key of the session item
	//	isExternal (bool): if this should be treated as an external item
	// returns (boolean): 				
	//	true: if exists
	//	false: if does not exists
	this.has = function(key, isExternal) {
		// read from either window.sessionStorage or from window.name
		var found = false;
		if (key) {
			// update key with prefix (if not an external item)
			if (!isExternal) {
				key = self.config.sessionStorePrefix + key;
			};	
				
			if (window.sessionStorage) {
				found = (window.sessionStorage.getItem(key) ? true : false);
			} else {
				var sessionData = [];
				if (!isEmpty(window.name)) {
					sessionData = JSON.parse(window.name);
					var idx = -1;
					$.each(sessionData, function(index, item) {
						if (item.k === key) {
							idx = index;
							return false; // break
						};
					});
					if (idx !== -1) {
						found = true;
					};
				};
			};
		};

		// return
		return found;
	};
	
	// clear all values stored in session
	// Note: external items are not removed
	// returns (void): 					
	this.clear = function() {
		// clear either window.sessionStorage or window.name
		if (window.sessionStorage) {
			// remove all items which are stored by this plugin
			var allItems = self.items();
			$.each(allItems, function(i, key) {
				window.sessionStorage.removeItem(self.config.sessionStorePrefix + key);
			});
		} else {
			// re-store all items which are not of this plugin
			var sessionData = [];
			var newSessionData = [];
			if (!isEmpty(window.name)) {
				sessionData = JSON.parse(window.name);
				// get all items which does not belong to this plugin
				$.each(sessionData, function(index, item) {
					if (item.k.indexOf(self.config.sessionStorePrefix) === -1) {
						newSessionData.push(item);
					};
				});
				
				// clear everything 
				window.name = "";
				
				// re-push others
				window.name = JSON.stringify(newSessionData);
			};			
		};
		
		// reset
		self.onInit();
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: sessionProperty
  *	 Target: $f.utils
  *  Dependencies: 
  *		- $f
  *		- $f.utils
  *  Functionality:
  *		- this adds sessionProperty class definition and associated factory implementation.
  *
  */
(function($f) {	$f.extend.feature("sessionProperty", "utils", "dc112a0a-c5e2-4080-9bc7-c485fb6f6e6f", function(self) {
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "sessionProperty Definition",
		description: "Adds sessionProperty class definition and associated factory implementation in utils."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// object operations
	this.object = {
		// general purpose extensible (via features) factory implementation
		factory: {
			// shortcut instanceof check methods
			instanceOf: {
				// check if given object is an instance of sessionProperty class
				// params:
				//	object (object): object instance to check for
				// returns (boolean): true, if instance of, false otherwise
				sessionProperty: function(object) {
					// return
					return self.object.factory.isInstanceOf(object, "sessionProperty");
				}
			},
		
			// shortcuts factory methods
			getNew: {
				// creates and return a new instance of sessionProperty class
				// params:
				//  args (...): arguments any number of
				// returns (object): instance of created object, null otherwise				
				sessionProperty: function() {
					// return
					return self.object.factory.create("sessionProperty", arguments);
				}
			},
		
			// class definitions
			classes: {
				// sessionProperty class definition
				sessionProperty: function(plugin, sessionItemName, getter) { 
					var _plugin = plugin; 
					var _sessionItemName = sessionItemName; 
					var _getter = getter; 
					this.get = function() { 
						return ((_getter) ? _getter() : _plugin.session[_sessionItemName].get()); 
					}; 
				}
			}
		}
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: states
  *  Dependencies: 
  * 	- $f
  *  Functionality:
  *		- this plugin provides client-side state management, by maintaining the state variables 
  *		  across browser reload.
  *		- it does process other plugins for following property, if defined
  *			> state
  *
  */
(function($f) {	$f.extend.system("states", "7aa1c134-e8fa-464e-afd8-289bc2f61552", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "States",
		description: "Provides client-side state management, by maintaining the state variables (defined under state property) across page-refresh cycles."
	};

	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// check if necessary settings / features available for this plugin to run
		var isSuccess = false;
		if (window.sessionStorage || 
			$f.config.options.isEnableLocalFileSystemAccess ||
			$f.config.options.isFallbackToSessionStoreWhenNoFileSystem) {
			isSuccess = true;
		};

		// return
		return isSuccess;
	};
	
	// reset handler
	// returns: (void)
	this.onReset = function() {
		// clear self 
		self.clear();
	};
	
	// plugin configuration
	this.config = {
		// name of the JSON file in which state data of the plugins is saved to maintain across reload continuity of states
		// this will be used only if session storage is not available in browser
		statesJSON: "%TEMP%/app.states.json",
		
		// name of the key used to store application state in sessionStorage or in $f.session's fallback store
		statesKey: "_statesData",
		
		// can this plugin configure other plugins
		// if this is set to true, after plugins are initialized, these will be
		// given to this plugin's configure method to do required configuration
		canConfigurePlugins: true,
		
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 250					
	};		
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// last loaded states object
		data: {}
	};
	
	// configure given plugin 
	// this is called for each plugin if canConfigurePlugins is set to true
	// params:
	//	plugin (object): plugin object to configure
	//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
	//                                        this plugin otherwise should also be done now with
	//                                        this plugin, because this is being loaded after all
	//                                        batch processing is done at load time
	//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
	// 										    a new feature is added to plugin which may have added
	//											some members those required reconfiguration	
	// returns (void):			
	this.configure = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {
		// load state of the plugin (it will load states only if new session)
		if (isPerformOnLoadProcessAlso && !isReconfigureOnNewFeatureAdd) {
			self.load(plugin);
		};
	};
	
	// load handler
	// returns (void):
	this.onLoad = function() {
		// load states back from sessionStorage or from local temp file (if not in a new session)
		var states = null;
		if (!$f.sess.isNew.get()) {
			// load states from sessionStorage
			if (window.sessionStorage) {
				states = window.sessionStorage.getItem(self.config.statesKey);
				if (states) {
					states = JSON.parse(states);
				};
			} else if ($f.config.options.isEnableLocalFileSystemAccess) {
				// load states from local file system
				var stateTempFile = self.config.statesJSON;
				if (stateTempFile) {
					states = {};
					if ($f.IO.file.isExistsLocally($f.IO.folder.getCompletePath(stateTempFile))) {
						// load states fron JSON file
						states = $f.files.JSON.load(stateTempFile, "");
						if (!states) {
							states = {};
						};
					};						
				};
			} else if ($f.config.options.isFallbackToSessionStoreWhenNoFileSystem) {
				// load states from local session store
				if ($f.sess) {
					states = $f.sess.get(self.config.statesKey, "", true);
					if (states) {
						states = JSON.parse(states);
					} else {
						states = null;
					};
				};
			};
		
			// set states data
			if (states) {
				self.vars.data = states;
			};

			// load states data into framework and all plugins
			if (self.vars.data) {
				$.each($f.all.plugins("a"), function(i, plugin) {
					if (plugin.state) {
						self.load(plugin);
					};
				});
			};
		};
	};

	// unload handler
	// returns: (void)
	this.onUnload = function() {
		// save states of all plugins either in a state file or in 
		// all plugins must have a unique ID or else states will grabble
		// gather state of all plugins and framework into one object
		var states = {};
		if (self.vars.data) {
			// starting with last states is the key to maintain states of all plugins (especially pages, modules, 
			// masters etc. even if they are not loaded because of their optional and user controlled loading 
			// behavior)
			states = self.vars.data; 
		};
		$.each($f.all.plugins("a"), function(i, plugin) {
			if (plugin.state) {
				// by default save state
				var isSaveState = true;
				
				// special handling for page, master, view and pane plugins
				// these types of plugins can optionally opt not 
				// maintain their state for the session when this is not a reload scenario
				// this could be for serval obviuos reasons
				// such as page is loaded only once during entire session
				// so state might need while reloading the page but not when 
				// navigating out from page
				if ($f.nav) {
					if (!$f.nav.isReloading.get() && 
						(plugin.handle.isPage() || 
						 plugin.handle.isMaster() ||
						 plugin.handle.isView() ||
						 plugin.handle.isPane())) {
						if (plugin.config && plugin.config.isKeepStateAlive) {
							isSaveState = plugin.config.isKeepStateAlive;
						};
					};
				};
				
				// save
				if (isSaveState) {
					// inform plugin
					if (isFunction(plugin.beforeSaveState)) {
						plugin.beforeSaveState();
						
						// forward to features
						plugin.forwardToFeatures("beforeSaveState");
					};				
					
					// pick state
					states[plugin.handle.id] = plugin.state;
				} else {
					// delete this entry from states
					delete states[plugin.handle.id];
				};
			};
		});
		
		// save it in sessionStorage if available or else in a local 
		// temp file if enabled or in local session (which must be going to its 
		// fallback when sessionStore is not available)
		if (window.sessionStorage) {
			// save states in sessionStorage
			window.sessionStorage.setItem(self.config.statesKey, JSON.stringify(states));			
		} else if ($f.config.options.isEnableLocalFileSystemAccess) {
			// save states in JSON file
			var stateTempFile = self.config.statesJSON;
			if (stateTempFile) {
				$f.files.JSON.save(stateTempFile, "", states);
			};
		} else if ($f.config.options.isFallbackToSessionStoreWhenNoFileSystem) {
			// save states in local session store
			if ($f.sess) {
				$f.sess.set(self.config.statesKey, JSON.stringify(states), true);
			};
		} else {
			$f.error("No fallback to store states.", false, false);
		};
	};
	
	// load states of specified plugins (if not in a new session)
	// a direct call is generally used for plugins which are loaded after states was loaded
	// params:
	//	plugin (object): plugin object for which states are to be loaded
	// returns (void):
	this.load = function(plugin) {
		if (!$f.sess.isNew.get() && self.vars.data && plugin && plugin.state) {
			// load state for given plugin
			var stateValue = self.vars.data[plugin.handle.id];
			if (stateValue) { 
				// load plugin's state
				plugin.state = stateValue;
				
				// inform plugin
				if (isFunction(plugin.afterLoadState)) {
					plugin.afterLoadState();
					
					// forward to features
					plugin.forwardToFeatures("afterLoadState");
				};
			};
		};
	};

	// delete stored states of all plugins
	// returns (void):
	this.clear = function() {
		if (window.sessionStorage) {
			// clear states in sessionStorage
			window.sessionStorage.removeItem(self.config.statesKey);	
		} else if ($f.config.options.isEnableLocalFileSystemAccess) {
			// clear states in JSON file
			var stateTempFile = self.config.statesJSON;
			if (stateTempFile) {
				$f.files.JSON.save(stateTempFile, "", {});
			};
		} else if ($f.config.options.isFallbackToSessionStoreWhenNoFileSystem) {
			// clear states in session store (setting null will delete it)
			if ($f.sess) {
				$f.sess.set(self.config.statesKey, null, true);
			};
		};

		// clear from internal memory as well
		self.vars.data = {};
	};

	// number of items that are currently stored in states
	// returns (number): count of items in states
	this.count = function() {
		// count
		var length = 0;
		$.each(self.vars.data, function(name, value) {
			length++;
		});
		
		// return
		return length;
	};
	
	// item names array that are currently stored in states
	// returns (array): array of item names that are stored in states
	this.items = function() {
		// gather names
		var items = [];
		$.each(self.vars.data, function(name, value) {
			items.push(name);
		});
		
		// return
		return items;
	};
	
	// check if specified key exists in states
	// params:
	//	key (string): id of the state that is to be read
	// returns (boolean): 				
	//	true: if exists
	//	false: if does not exists
	this.has = function(key) {
		// check if defined
		var isAvailable = false;
		var value = self.vars.data[key];
		if (isDefined(value)) { 
			isAvailable = true;
		};
		
		// return
		return isAvailable;
	};
	
	// get state by known id
	// params:
	//	key (string): id of the state that is to be read
	// returns (object): null if not found, else value object
	this.get = function(key) {
		// get state for given id
		var value = self.vars.data[key];
		if (!isDefined(value)) { 
			value = null;
		};
		
		// return
		return value;
	};
	
	// set state by known id
	// params:
	//	key (string): id of the state that is to be written to
	// 	value (object): state item value (must be JSON serializable) OR null (it item is to be removed)		
	// returns (void): 
	this.set = function(key, value) {
		if (!isNull(value)) {
			// add/update state for given id
			self.vars.data[key] = value;
		} else {
			delete self.vars.data[key];
		};
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: stateProperty
  *	 Target: $f.utils
  *  Dependencies: 
  *		- $f
  *		- $f.utils
  *  Functionality:
  *		- this adds stateProperty class definition and associated factory implementation.
  *
  */
(function($f) {	$f.extend.feature("stateProperty", "utils", "5ae5e75e-fa7c-498f-ae2e-f1027f2ac6c2", function(self) {
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "stateProperty Definition",
		description: "Adds stateProperty class definition and associated factory implementation in utils."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// object operations
	this.object = {
		// general purpose extensible (via features) factory implementation
		factory: {
			// shortcut instanceof check methods
			instanceOf: {
				// check if given object is an instance of stateProperty class
				// params:
				//	object (object): object instance to check for
				// returns (boolean): true, if instance of, false otherwise
				stateProperty: function(object) {
					// return
					return self.object.factory.isInstanceOf(object, "stateProperty");
				}
			},
		
			// shortcuts factory methods
			getNew: {
				// creates and return a new instance of stateProperty class
				// params:
				//  args (...): arguments any number of
				// returns (object): instance of created object, null otherwise				
				stateProperty: function() {
					// return
					return self.object.factory.create("stateProperty", arguments);
				}
			},
		
			// class definitions
			classes: {
				// stateProperty class definition
				stateProperty: function(plugin, stateItemName, getter) { 
					var _plugin = plugin; 
					var _stateItemName = stateItemName; 
					var _getter = getter; 
					this.get = function() { 
						return ((_getter) ? _getter() : _plugin.state[stateItemName]); 
					}; 
				}
			}
		}
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: pages
  *	 Target: $f
  *  Dependencies: 
  *		- fluid core
  *  Functionality:
  *		- this adds pages feature to framework core
  *
  */
(function($f) {	$f.extend.feature("pages", "root", "bde337b2-2767-4b51-ab48-6d552024377e", function(self) {

	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "Pages",
		description: "Add pages functionality to core framework."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// add to extend function
	this.FUNC_extend = {
		// forwards to extend
		page: function(id, extender) {
			// forward
			return $f.extend("page", id, extender);
		},

		// add to page function
		FUNC_page: {
			// forwards to extend
			fromFile: function(pluginJSFile, callback) {
				// forward
				return $f.extend.fromFile(pluginJSFile, "page", "plugin", callback);
			}	
		}
	};

	// private functions 
	// not for public use
	// backward compatibility is not guranteed
	this.p = {
		// plugin functionality
		plugins: {
			// plugin types
			types: {
				page: "page"
			},

			// feature targets
			// returns (array): returns an array of plugin objects of a particular type on which a feature 
			//                  is to be added when requested
			featureTargets: {
				page: function() {
					// create list
					var plugins = [];
					if ($f.page) {
						plugins.push($f.page);
					};
					
					// return
					return plugins;
				}
			},
			
			// plugin classes
			// convention here is that except pluginBase, which is base of all plugins,
			// for every other type of plugin, the name should be "<typeName>PluginBase"
			// where <typeName> is the string defined for type in plugins.types above
			classes: {
				// extended definition for page plugin - over base definition
				pagePluginBase: function(self) {
					// plugin handle
					this.handle = {
						// if app plugin
						isAppPlugin: true,
						
						// is default page
						isDefaultPage: function() {
							return self.handle.name === "page_default";
						},
					
						// extension options that are to be used for extension 
						extensionOptions: {
							ignore: "'url', 'href', 'args', 'isReload', 'show', 'hide', 'refresh', 'beforeNavigationComplete', ",
							partialCopy: {
								p: "'getLayout', 'getStyles', ",
								vars: "'isBeforeNavigationCompleteProcessed', "
							}	
						}
					};
					
					// plugin variables
					// value of these variables is NOT maintained across page refresh
					this.vars = {
						// controls that beforeNavigationComplete do not run twise
						isBeforeNavigationCompleteProcessed: false
					};
					
					// plugin configuration
					this.config = {
						// zIndex of the plugin controls the sequence of calling
						// onLoad, onReady and onUnload handlers of the plugins
						// with respect to each other
						// valid values are between 0 to 99999. Values between 0 to 9999
						// and 90001 upwards are reserved for framework plugins. 
						// For custom plugins use any value between 10000 to 90000.
						zIndex: 95000		
					};
					
					// private functions 
					// not for public use
					// backward compatibility is not guranteed
					this.p = {
						// picks the applied layout from given layout object
						// params:
						//	layout (object): layout object to scan
						//	plugin (object): plugin in which context this layout is being looked for
						// returns (string): applied layout file name
						getLayout: function(layout, plugin) {
							// detect
							if (!isDefined(layout)) {
								layout = "";
							};
							var layoutFile = "";
							if (isString(layout)) {
								// to keep things simple it also supports a plain string version 
								// of layout definition as well
								// Note: This string can also be directly embedded HTML in that case
								// it will be prefixed with "html:" token
								layoutFile = layout;
								
								// if layout string is empty, then try to auto-wire html with plugin in context
								if (isEmpty(layout) && plugin) {
									if (plugin.handle.file) {
										layoutFile = plugin.handle.file.replace(".*.js", ".html");
									};
								};
							} else {
								if ($f.env.browser.isDesktop && $f.utils.object.has(layout, "desktop.markup")) {
									layoutFile = layout.desktop.markup;
								} else if ($f.env.browser.isTablet) {
									var o = $f.page.orientation();
									if (o === 0) {
										// portrait
										if ($f.utils.object.has(layout, "tablet.portrait.markup")) {
											layoutFile = layout.tablet.portrait.markup;
										}
									} else {
										// landscape
										if ($f.utils.object.has(layout, "tablet.landscape.markup")) {
											layoutFile = layout.tablet.landscape.markup;
										};
									};

									// fallback
									if (isEmpty(layoutFile) && $f.utils.object.has(layout, "tablet.markup")) {
										layoutFile = layout.tablet.markup;
									};
								} else if ($f.env.browser.isMobile) {
									var o = $f.page.orientation();
									if (o === 0) {
										// portrait
										if ($f.utils.object.has(layout, "mobile.portrait.markup")) {
											layoutFile = layout.mobile.portrait.markup;
										};
									} else {
										// landscape
										if ($f.utils.object.has(layout, "mobile.landscape.markup")) {
											layoutFile = layout.mobile.landscape.markup;
										};
									};

									// fallback
									if (isEmpty(layoutFile) && $f.utils.object.has(layout, "mobile.markup")) {
										layoutFile = layout.mobile.markup;
									};
								};
								
								// ultimate fallback
								if (isEmpty(layoutFile) && layout.markup) {
									layoutFile = layout.markup;
								};
							};
							
							// return
							return layoutFile;
						},
						
						// picks the applied set of styles from given layout object
						// params:
						//	layout (object): layout object to scan
						// returns (array): array of CSS files
						getStyles: function(layout) {
							// detect
							var styles = [];
							if (isString(layout)) {
								// to keep things simple it also supports a plain string version 
								// of layout definition as well
								// in that case no styles are present
								styles = [];
							} else {
								if ($f.env.browser.isDesktop && $f.utils.object.has(layout, "desktop.styles")) {
									styles = layout.desktop.styles;
								} else if ($f.env.browser.isTablet) {
									var o = $f.page.orientation();
									if (o === 0) {
										// portrait
										if ($f.utils.object.has(layout, "tablet.portrait.styles")) {
											styles = layout.tablet.portrait.styles;
										};
									} else {
										// landscape
										if ($f.utils.object.has(layout, "tablet.landscape.styles")) {
											styles = layout.tablet.landscape.styles;
										};
									};

									// fallback
									if (styles.length === 0 && $f.utils.object.has(layout, "tablet.styles")) {
										styles = layout.tablet.styles;
									};
								} else if ($f.env.browser.isMobile) {
									var o = $f.page.orientation();
									if (o === 0) {
										// portrait
										if ($f.utils.object.has(layout, "mobile.portrait.styles")) {
											styles = layout.mobile.portrait.styles;
										};
									} else {
										// landscape
										if ($f.utils.object.has(layout, "mobile.landscape.styles")) {
											styles = layout.mobile.landscape.styles;
										};
									};

									// fallback
									if (styles.length === 0 && $f.utils.object.has(layout, "mobile.styles")) {
										styles = layout.mobile.styles;
									};
								};
								
								// ultimate fallback
								if (styles.length === 0 && layout.styles) {
									styles = layout.styles;
								};
							};
							
							// return
							return styles;			
						}
					};
					
					// page href
					this.href = $f.utils.object.factory.getNew.readOnlyProperty({});
					
					// page args
					this.args = $f.utils.object.factory.getNew.readOnlyProperty({});
					
					// url of page
					this.url = $f.utils.object.factory.getNew.readOnlyProperty("");
					
					// defines if page is reloading
					this.isReload = $f.utils.object.factory.getNew.readOnlyProperty(false);
					
					// show page
					// returns (void):
					this.show = function() {
						// show screen
						$("#" + $f.env.container.screen()).fadeIn();
					};
					
					// hide page
					// params:
					//	showAfterMilliseconds (number): Optional. Show page again after specified millseconds
					// returns (void):
					this.hide = function(showAfterMilliseconds) {
						// hide screen
						$("#" + $f.env.container.screen()).fadeOut();
						
						// set reshow
						if (showAfterMilliseconds) { 
							setInterval(function() {
								// show again
								self.show();
							}, showAfterMilliseconds);
						};
					};
				
					// called everything related to page navigation is done
					// and onNavigationComplete is about to be called
					// this can be used to do any further processing by base class
					// 
					this.beforeNavigationComplete = function() {
						if (!self.vars.isBeforeNavigationCompleteProcessed) {
							// set 
							self.vars.isBeforeNavigationCompleteProcessed = true;
							
							// forward to all features that can handle a forward
							self.forwardToFeatures("beforeNavigationComplete");
							
							// orientation change setup
							if (!$f.env.browser.isDesktop && $f.page.config && $f.page.config.isDetectOrientationChange) {
								$(window).bind('orientationchange', function(e) { 
									// let navigator renavigate to same page
									$f.nav.navigateOnOrientationChange();
								});				
							};
						};
					};
					
					// refreshes the page - same behavior as of F5
					// returns (void):
					this.refresh = function() {
						// forward to navigator
						$f.nav.reload();
					};
				}
			}
		}
	};	
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: page
  *  Dependencies: 
  * 	- fluid core
  *  Functionality:
  *		- this page (plugin) provides a general purpose error page.
  *		- it does not process any other plugins.
  *
  */
(function($f) { $f.extend("page", "page_default", "", "8ff89ea0-e795-4285-92b1-859e2a4a2d36", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin handle
	this.handle = {
		// if system plugin
		isSystemPlugin: true,
		
		// if app plugin
		isAppPlugin: false
	};
	
	// plugin info
	this.info = {
		title: "Default Page",
		description: "A default page generally used to show page load time error (mostly 404) details."
	};

	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// set it's layout (using default string approach)
		self.config.layout = $f.config.options.error404Html;
		
		// return
		return true; 
	};
	
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 5000
	};
}); }(fluid));

/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: structuralElements
  *	 Target: $f.environment
  *  Dependencies: 
  *		- $f
  *		- $f.environment
  *  Functionality:
  *		- this adds structural elements information to environment
  *
  */
(function($f) {	$f.extend.feature("structuralElements", "environment", "fbaed97e-d709-4b9a-8c84-53642a7dd611", function(self) {

	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "Structural Elements",
		description: "Add structural elements information to environment."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// startup html known containers
	this.container = {
		// parent container of...
		parentOf: {
			// parent of container in page layout where main content container is placed
			// returns (string): DOM element id 
			pageMainContent: function() { 
				// return
				return "_" + self.container.pageMainContent();
			},
			
			// parent of container in startup layout where emulator is placed
			// returns (string): DOM element id (configured or default)
			emulator: function() {
				// return
				return "_" + self.container.emulator();	
			},
			
			// parent of container in startup layout where screen is placed
			// returns (string): DOM element id (configured or default)
			screen: function() {
				// return
				return "_" + self.container.screen();	
			},
			
			// parent of container in startup layout where host container is placed
			// returns (string): DOM element id 
			host: function() {
				// return
				return "_" + self.container.host();				
			},
			
			// parent of container in host layout where master container is placed
			// returns (string): DOM element id 
			master: function() { 
				// return
				return "_" + self.container.master();				
			},
			
			// parent of container in master page layout where page container is placed
			// returns (string): DOM element id 
			page: function() { 
				// return
				return "_" + self.container.page();
			},
			
			// parent of container in page layout where views are placed
			// returns (string): DOM element id 
			views: function() { 
				// return
				return "_" + self.container.views();
			},
			
			// parent of container in startup layout where top pane is placed
			// returns (string): DOM element id (configured or default)
			topPane: function() {
				// return
				return "_" + self.container.topPane();				
			},	

			// parent of container in startup layout where left pane is placed
			// returns (string): DOM element id (configured or default)
			leftPane: function() {
				// return
				return "_" + self.container.leftPane();				
			},	

			// parent of container in startup layout where right pane is placed
			// returns (string): DOM element id (configured or default)
			rightPane: function() {
				// return
				return "_" + self.container.rightPane();				
			},	

			// parent of container in startup layout where bottom pane is placed
			// returns (string): DOM element id (configured or default)
			bottomPane: function() {
				// return
				return "_" + self.container.bottomPane();				
			},	
			
			// parent of container in startup layout where center pane is placed
			// returns (string): DOM element id (configured or default)
			centerPane: function() {
				// return
				return "_" + self.container.centerPane();				
			}
		},
		
		// container in page layout where progressive page content is loaded
		// returns (string): DOM element id (configured or default)			
		breadCrumbs: function() {
			var containerElementId = $f.config.options.breadCrumbsContainerElementId;
			// give page a chance to override global setting
			if ($f.page.config && $f.page.config.breadCrumbsContainerElementId) {
				var elementId = $f.page.config.breadCrumbsContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "breadcrumbs"; // inbuilt default
			};			

			// return
			return containerElementId;			
		},
		
		// container in page layout where wizard steps are shown
		// returns (string): DOM element id (configured or default)			
		wizard: function() {
			var containerElementId = $f.config.options.wizardContainerElementId;
			// give page a chance to override global setting
			if ($f.page.config && $f.page.config.wizardContainerElementId) {
				var elementId = $f.page.config.wizardContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "wizard"; // inbuilt default
			};			

			// return
			return containerElementId;			
		},			
		
		// container in page layout where progressive page content is loaded
		// returns (string): DOM element id (configured or default)			
		progressivePageContent: function() {
			var containerElementId = $f.config.options.progressivePageContentContainerElementId;
			// give page a chance to override global setting
			if ($f.page.config && $f.page.config.progressivePageContentContainerElementId) {
				var elementId = $f.page.config.progressivePageContentContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "progressive_content"; // inbuilt default
			};			

			// return
			return containerElementId;			
		},
		
		// container in page layout where main content is placed
		// returns (string): DOM element id (configured or default)
		pageMainContent: function() {
			var containerElementId = $f.config.options.mainContentContainerElementId;
			// give page a chance to override global setting
			if ($f.page.config && $f.page.config.mainContentContainerElementId) {
				var elementId = $f.page.config.mainContentContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "content"; // inbuilt default
			};			

			// return
			return containerElementId;
		},
		
		// container in startup layout where infoBar layout is placed
		// returns (string): DOM element id (configured or default)
		infoBar: function() {
			var elementId = "";
			// show in screen or in main container
			if ($f.emulator && $f.emulator.isEmulating.get()) {
				elementId = "screenInfoBar"; // inbuilt default
			} else {
				elementId = "containerInfoBar"; // inbuilt default
			};
		
			// return
			return elementId; 
		},			

		// container in startup layout which represents screen
		// returns (string): DOM element id (configured or default)
		screen: function() {
			// return
			return "screen"; // inbuilt default		
		},
		
		// container in startup layout which represents emulator
		// returns (string): DOM element id (configured or default)
		emulator: function() {
			// return
			return "emulator"; // inbuilt default				
		},
		
		// container in startup layout where host layout content is placed
		// returns (string): DOM element id (configured or default)
		host: function() {
			// return
			return "host"; // inbuilt default				
		},
		
		// container in host layout where master layout content is placed
		// returns (string): DOM element id (configured or default)
		master: function() {
			var containerElementId = $f.config.options.masterContainerElementId;
			if ($f.app) {
				// give current theme a chance to override global setting
				if ($f.app.theme) {
					var theme = $f.app.theme();
					if (theme && theme.masterContainerElementId) {
						containerElementId = theme.masterContainerElementId;
					};
				};
				
				// pick app level default if required
				if (isEmpty(containerElementId) && $f.app.config && $f.app.config.masterContainerElementId) {
					containerElementId = $f.app.config.masterContainerElementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "master"; // inbuilt default
			};	

			// return
			return containerElementId;					
		},
		
		// container in master page layout where page layout is placed
		// returns (string): DOM element id (configured or default)
		page: function() {
			var containerElementId = $f.config.options.pageContainerElementId;
			// give master page a chance to override global setting
			if ($f.master && $f.master.config && $f.master.config.pageContainerElementId) {
				var elementId = $f.master.config.pageContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "page"; // inbuilt default
			};			
			
			// return
			return containerElementId;				
		},
		
		// container in page layout where views layouts are placed
		// returns (string): DOM element id (configured or default)
		views: function() {
			var containerElementId = $f.config.options.viewsContainerElementId;
			// give page a chance to override global setting
			if ($f.page.config && $f.page.config.viewsContainerElementId) {
				var elementId = $f.page.config.viewsContainerElementId;
				if (elementId) {
					containerElementId = elementId;
				};
			};
			
			if (isEmpty(containerElementId)) {
				containerElementId = "views"; // inbuilt default
			};			
			
			// return
			return containerElementId;				
		},
		
		// container in page layout where view layout of specified view object is/will be placed
		// returns (string): DOM element id (configured or default)
		view: function(view) {
			return "view_" + view.handle.id;
		},
		
		// container in startup layout which represents panes root
		// returns (string): DOM element id (configured or default)
		panes: function() {
			// return
			return "panes"; // inbuilt default				
		},
		
		// container in startup layout which represents top pane
		// returns (string): DOM element id (configured or default)
		topPane: function() {
			// return
			return "topPane"; // inbuilt default				
		},
		
		// container in startup layout which represents left pane
		// returns (string): DOM element id (configured or default)
		leftPane: function() {
			// return
			return "leftPane"; // inbuilt default				
		},		
		
		// container in startup layout which represents right pane
		// returns (string): DOM element id (configured or default)
		rightPane: function() {
			// return
			return "rightPane"; // inbuilt default				
		},			
		
		// container in startup layout which represents bottom pane
		// returns (string): DOM element id (configured or default)
		bottomPane: function() {
			// return
			return "bottomPane"; // inbuilt default				
		},			
		
		// container in startup layout which represents center pane
		// returns (string): DOM element id (configured or default)
		centerPane: function() {
			// return
			return "centerPane"; // inbuilt default				
		},
		
		// container in 404 layout where error message is shown
		// returns (string): DOM element id (configured or default)
		error: function() {
			var containerElementId = $f.config.options.errorMessageElementId;
			if (isEmpty(containerElementId)) {
				containerElementId = "error"; // inbuilt default
			};
			
			// return
			return containerElementId;				
		},
		
		// container in startup layout which contains waiting wheel
		// returns (string): DOM element id (configured or default)
		wait: function() {
			// return
			return "waitWheel"; // inbuilt default		
		}			
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: fluidProtocol
  *	 Target: $f.document
  *  Dependencies: 
  *		- $f
  *		- $f.document
  *  Functionality:
  *		- this add navigation support via fluid:\\ protocol feature to document
  *
  */
(function($f) {	$f.extend.feature("fluidProtocol", "document", "9c299d24-bb10-4af7-8046-4ebe588616d7", function(self) {

	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "fluid:\\ Protocol",
		description: "Add navigation support via fluid:\\ protocol to document."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// plugin configuration
	this.config = {
		// protocol prefixes
		fluidProtocol: "fluid://",
		jsProtocol: "javascript:",

		// delimiters/seperators/identifiers
		argsDelimiter: "$",
		argsSeperator: "&",
		argValueSeperator: "=",
		argExpressionIdentifier: "%",
		viewOrQualifiedNameDelimiter: "~",
		hashTagDelimiter: "#"
	};
	
	// process given href and take apt action
	// params: 
	//	href (string): an href string to be processed
	//				   	href can be of following types:
	//
	//					fluid:// protocol:
	//					PAGE:
	//					fluid://[relativePathOfPage/]pageJSFile.page[$param1Name=[paramValue | %JSExpression]][&param2Name=[paramValue | %JSExpression]][&...]
	//					fluid://[pathOfPageInAppRouteStructure/]pageNodeName[$param1Name=[paramValue | %JSExpression]][&param2Name=[paramValue | %JSExpression]][&...]
	//					VIEW:
	//					fluid://[relativePathOfPage/]pageJSFile.page~viewKey[$viewParam1Name=[paramValue | %JSExpression]][&...]
	//					fluid://[pathOfViewInAppRouteStructure/]viewNodeName[$viewParam1Name=[paramValue | %JSExpression]][&...]
	//					PANE:
	//					fluid://[relativePathOfPane/]paneJSFile.pane~paneQualifiedName[$param1Name=[paramValue | %JSExpression]][&param2Name=[paramValue | %JSExpression]][&...]
	//					fluid://[pathOfPaneInAppRouteStructure/]paneNodeName[$param1Name=[paramValue | %JSExpression]][&param2Name=[paramValue | %JSExpression]][&...]
	//					PLUGIN:
	//					fluid://[relativePathOfPlugin/]pluginJSFile.plugin~pluginQualifiedName
	//					MODULE:
	//					fluid://[relativePathOfPlugin/]pluginJSFile.module~moduleQualifiedName
	//					FEATURE:
	//					fluid://[relativePathOfPlugin/]pluginJSFile.feature
	//					FUNCTION:
	//					fluid://[functionQualifierObjectHierarchy/]functionName.func[$param1[&param2][&...]]
	//					COMMAND:
	//					fluid://builtInFunctionName.cmd[$param1[&param2][&...]]
	//					
	//					javascript calls:
	//					-----------------
	//					javascript:functionName([param1][,param2][,...]);[functionName([param1][,param2][,...]);[...;]]
	//					
	//					standard protocols:
	//					-------------------
	//					http://, ftp://, file://, www., etc. - they will be processed as is, in another tab/window
	// returns (boolean): 
	//	true: if href was processed
	//	false: if href was not processed
	this.href = function(href) {
		// parse and split first
		var isProcessed = true; // by default everything is processed
		var hrefObj = self.href.split(href);
		
		// if javascript, don't process this and let browser do it as required
		if (hrefObj.isJavaScript) {
			isProcessed = false;
		} else {
			if (hrefObj.isStandard) {
				// all standard URLs (except javascript url) are opened in a new tab or window (as per user settings in browser)
				window.open(hrefObj.url, '_blank');
				window.focus();
			} else {
				// page, view, pane, plugin, function, command
				if (hrefObj.type === "page" || hrefObj.type === "view") {
					// navigate to page or view
					$f.nav.go(hrefObj);								
				} else if (hrefObj.type === "pane") {
					// try to see if it is already loaded
					var pane = $f.get.plugin.byQualifiedName(hrefObj.qualifiedName, "pane");
					if (!pane) {
						// load and open pane
						$f.extend.pane.fromFile(hrefObj.jsFile, hrefObj.qualifiedName, function(data, isError) {
							if (!isError && hrefObj.qualifiedName) {
								// get pane
								pane = $f.get.plugin.byQualifiedName(hrefObj.qualifiedName, "pane");
								
								// open it if found
								if (pane) {
									pane.openASync(hrefObj.args);
								};
							}
						});
					} else {
						// open, if not already open
						// else - ignore this call
						if (!pane.isOpen.get()) {
							pane.openASync(hrefObj.args);
						};
					};
				} else if (hrefObj.type === "plugin") {
					// load plugin
					$f.extend.fromFile(hrefObj.jsFile, hrefObj.qualifiedName);
				} else if (hrefObj.type === "module") {
					// load module
					$f.extend.module.fromFile(hrefObj.jsFile, hrefObj.qualifiedName);
				} else if (hrefObj.type === "feature") {
					// load feature
					$f.extend.feature.fromFile(hrefObj.jsFile);
				} else if (hrefObj.type === "function" || hrefObj.type === "command") {
					// call function
					try {
						eval(hrefObj.expression);
					} catch (ex) {
						$f.error("Function/Command execution failed for '" + hrefObj.url + "'.", true, false, ex);													
					};
				} else {
					// unknown
					isProcessed = false; 
				};
			};
		};
		
		// return
		return isProcessed;
	};	
	
	// add to href function
	this.FUNC_href = {
		// break href into an object having all items as members
		// params:
		//	href (string): an href string to be processed
		// returns (object): href object, for which structure is as:
		//					 {
		//						url: url as is
		//						hashTag: hash tag equivelant of the url
		//						protocol: (fluid://, http://, etc.)
		//						isStandard: true|false, (if this is an standard protocol or fluid protocol)
		//						isJavaScript: true|false (if this is a javascript function)
		//						domain: domain name
		//						resource: resource name with path
		//						type: page, view, pane, plugin, module, feature, function, command
		//						route: route
		//						jsFile: plugin/page js file name
		//						view: view key
		//						qualifiedName: pane/module/plugin qualified name
		//						expression: function/command expression to execute
		//						args: {name: value, ...}
		//						argValues: []
		//						argsString: ""
		// 					 }
		split: function(href) {
			// replace any path placeholders in href
			href = $f.IO.folder.getResolvedPath(href, true);
			
			// create default 
			var hrefObject = {
				url: href,
				hashTag: "",
				protocol: "",
				isStandard: (href.indexOf(self.config.fluidProtocol) !== 0),
				isJavaScript: (href.indexOf(self.config.jsProtocol) === 0), 
				isAppRoute: false,
				domain: "",
				type: "",
				route: "",
				resource: "",
				jsFile: "", 
				view: "",
				qualifiedName: "",
				expression: "",
				args: null,
				argValues: null,
				argsString: ""
			};
			
			// get protocol
			var isStandard = hrefObject.isStandard;
			var isJavaScript = hrefObject.isJavaScript;
			if (!isStandard) {
				hrefObject.protocol = self.config.fluidProtocol.split("://")[0];
			} else if (isJavaScript) {
				hrefObject.protocol = self.config.jsProtocol.split(":")[0];
			} else {
				hrefObject.protocol = href.split("://")[0];
			};
			
			// get domain
			if (isStandard && !isJavaScript) {
				hrefObject.domain = href.split("://")[1].split("/")[0];
			};
			
			// get route and approute
			var routeStartAt = -1;
			var routeEndAt = -1;
			var route = href.split("://")[1];
			if (isStandard) {
				// ex: http://html5test.com/results/desktop.html?abc=1
				routeStartAt = route.indexOf("/") + 1;
				routeEndAt = route.lastIndexOf("/");
			} else if (!isJavaScript) {
				// ex1: fluid://abc/xyz/page1.page$abc=1
				// ex2: fluid://abc/xyz$abc=1
				// ex3: fluid://abc/xyz/page1.page~view1$abc=1
				// ex4: fluid://page1.page$abc=1
				// ex5: fluid://%APP%/abc/xyz/file1.plugin~pluginQualifiedName
				// ex6: fluid://%APP%/abc/xyz/module1.module~moduleQualifiedName
				// ex7: fluid://%APP%/abc/xyz/feature1.feature
				// ex8: fluid://%APP%/abc/xyz/pane1.pane~paneQualifiedName$abc=1
				routeStartAt = 0;
				if (route.indexOf(".") !== -1) {
					if (route.indexOf("/") !== -1) {
						routeEndAt = route.lastIndexOf("/");
					};
				} else {
					// since no resource is given, this is app route
					hrefObject.isAppRoute = true;
					
					if (route.indexOf(self.config.argsDelimiter) !== -1) {
						routeEndAt = route.indexOf(self.config.argsDelimiter);
					} else {
						routeEndAt = route.length;
					};
				};
			};
			if (routeStartAt !== -1 && routeEndAt !== -1) {
				route = route.substring(routeStartAt, routeEndAt);
				hrefObject.route = route;
			};
			
			// get resource
			var routeParameters = "";
			var viewKeyORQualifiedName = "";
			if (!isJavaScript) {
				if (hrefObject.isAppRoute && hrefObject.route && $f.app && $f.app.routes) {
					// resolve appRoute to get resource
					hrefObject.resource = $f.app.routes.resolve(hrefObject.route)

					// resolve any path placeholders in resolved route
					hrefObject.resource = $f.IO.folder.getResolvedPath(hrefObject.resource, true);

					// strip off parameters given on route itself
					var items = hrefObject.resource.split(self.config.argsDelimiter);
					hrefObject.resource = items[0];
					routeParameters = items[1];
					if (!routeParameters) {
						routeParameters = "";
					};
				} else {
					hrefObject.resource = href.substring(href.lastIndexOf("/") + 1).split(self.config.argsDelimiter)[0];
				};
				
				// strip-off viewKey/QualifiedName, if any
				var items = hrefObject.resource.split(self.config.viewOrQualifiedNameDelimiter);
				hrefObject.resource = items[0];
				viewKeyORQualifiedName = items[1];
			};

			// get type, jsFile, view and QualifiedName
			if (!isStandard && !isJavaScript) {
				// get url to further work on
				var url = "";
				if (hrefObject.isAppRoute) { 
					url = hrefObject.resource;			
				} else {
					url = href;
				};
				
				// process url
				if (url.indexOf("." + $f.config.options.pageExtensionInUrl) !== -1) {
					if (viewKeyORQualifiedName) {
						hrefObject.type = "view";
						// set viewKey
						hrefObject.view = viewKeyORQualifiedName;
					} else {
						hrefObject.type = "page";
					};
					hrefObject.jsFile = hrefObject.resource.replace("." + $f.config.options.pageExtensionInUrl, ".*.js");
					if (!hrefObject.isAppRoute) {
						if (!isEmpty(hrefObject.route)) {
							hrefObject.jsFile = hrefObject.route + "/" + hrefObject.jsFile;
						};
					};
				} else if (url.indexOf("." + $f.config.options.paneExtensionInUrl) !== -1) {
					hrefObject.type = "pane";
					hrefObject.jsFile = hrefObject.resource.replace("." + $f.config.options.paneExtensionInUrl, ".*.js");
					if (!isEmpty(hrefObject.route)) {
						hrefObject.jsFile = hrefObject.route + "/" + hrefObject.jsFile;
					};
					if (viewKeyORQualifiedName) {
						// set QualifiedName
						hrefObject.qualifiedName = viewKeyORQualifiedName;
					};
				} else if (url.indexOf("." + $f.config.options.pluginExtensionInUrl) !== -1) {
					hrefObject.type = "plugin";
					hrefObject.jsFile = hrefObject.resource.replace("." + $f.config.options.pluginExtensionInUrl, ".*.js");
					if (!isEmpty(hrefObject.route)) {
						hrefObject.jsFile = hrefObject.route + "/" + hrefObject.jsFile;
					};
					if (viewKeyORQualifiedName) {
						// set QualifiedName
						hrefObject.qualifiedName = viewKeyORQualifiedName;
					};
				} else if (url.indexOf("." + $f.config.options.moduleExtensionInUrl) !== -1) {
					hrefObject.type = "module";
					hrefObject.jsFile = hrefObject.resource.replace("." + $f.config.options.moduleExtensionInUrl, ".*.js");
					if (!isEmpty(hrefObject.route)) {
						hrefObject.jsFile = hrefObject.route + "/" + hrefObject.jsFile;
					};
					if (viewKeyORQualifiedName) {
						// set QualifiedName
						hrefObject.qualifiedName = viewKeyORQualifiedName;
					};
				} else if (url.indexOf("." + $f.config.options.featureExtensionInUrl) !== -1) {
					hrefObject.type = "feature";
					hrefObject.jsFile = hrefObject.resource.replace("." + $f.config.options.featureExtensionInUrl, ".*.js");
					if (!isEmpty(hrefObject.route)) {
						hrefObject.jsFile = hrefObject.route + "/" + hrefObject.jsFile;
					};
				} else if (url.indexOf("." + $f.config.options.commandExtensionInUrl) !== -1) {
					hrefObject.type = "command";
				} else if (url.indexOf("." + $f.config.options.functionExtensionInUrl) !== -1) {
					hrefObject.type = "function";
				};

			};
			
			// get args
			// args given on href gets precedence in case args are given on route itself
			if (hrefObject.type === "page" || hrefObject.type === "view" || hrefObject.type === "pane" || hrefObject.type === "function" || hrefObject.type === "command") {
				var args = "";
				var arg = null;
				var argName = "";
				var argValue = "";
				if (href.indexOf(self.config.argsDelimiter) !== -1) {
					args = href.split(self.config.argsDelimiter)[1];
				} else if (hrefObject.isAppRoute && !isEmpty(routeParameters)) {
					args = routeParameters;
				};
				if (!args) {
					args = "";
				};
				hrefObject.argsString = args;
				if (!isEmpty(args)) {			
					hrefObject.args = {};
					hrefObject.argValues = [];
					var pageArgsItems = [];
					if (args.indexOf(self.config.argsSeperator) !== -1) {
						pageArgsItems = args.split(self.config.argsSeperator);
					} else {
						pageArgsItems.push(args);
					};
					$.each(pageArgsItems, function(i, argItem) {
						if (hrefObject.type === "function" || hrefObject.type === "command") {
							argName = "arg" + i.toString();
							argValue = argItem;
						} else { // page, view or pane
							arg = argItem.split(self.config.argValueSeperator);
							argName = arg[0];
							argValue = arg[1];
						};
						
						// arg value can be a static value or a javascript expression
						// an expression is identified if value starts with %
						// if value starts with two %% means - user wants to pass one % as static value instead
						if (argValue.indexOf(self.config.argExpressionIdentifier + self.config.argExpressionIdentifier) === 0) {
							argValue = argValue.substring(1); // pick everything leaving initial % and use it as static
						} else if (argValue.indexOf(self.config.argExpressionIdentifier) === 0) {
							try {
								var argValueExpression = argValue.substring(1); // remove initial %
								argValue = eval(argValueExpression);
							} catch (ex) {
								$f.error("Failed to evaluate expression '" + argValueExpression + "' for argument '" + argName + "' in '" + href + "'.", true, false, ex);
								argValue = null;
							};
						} else {
							// use argValue as is
						};
						
						// add argName property
						// if user pass two same name arguments, it will be overwritten
						hrefObject.args[argName] = argValue;
						hrefObject.argValues.push(argValue);
					});			
				};
			};
			
			// get expression
			if (!isStandard && !isJavaScript) {
				var isValid = false;
				if (hrefObject.type === "command") {
					// ex: fluid://builtInFunctionName.cmd?param1&param2 => $f.functions.builtInFunctionName(...)
					hrefObject.expression = "$f.functions." + href.split("://")[1].split("." + $f.config.options.commandExtensionInUrl)[0];
					isValid = true;
				} else if (hrefObject.type === "function") {
					// ex: fluid://navigator/history/back.func?param1&param2 => $f.navigator.history.back(...)
					hrefObject.expression = "$f." + hrefObject.route.replace(/\//g, ".") + "." + hrefObject.resource.split("." + $f.config.options.functionExtensionInUrl)[0];			
					isValid = true;
				};
				if (isValid) {
					if (isNull(hrefObject.argValues)) {
						hrefObject.expression = hrefObject.expression + "()";
					} else {
						hrefObject.expression = hrefObject.expression + "(";
						$.each(hrefObject.argValues, function(i, argValue) {
							if (i !== 0) {
								hrefObject.expression = hrefObject.expression + ", ";
							};
							// Note: when evaluating this expression "hrefObj" must be available 
							hrefObject.expression = hrefObject.expression + "hrefObj.argValues[" + i.toString() + "]";
						});
						hrefObject.expression = hrefObject.expression + ")";
					};	
				};
			};
			
			// get/build hashtag
			if (!isJavaScript && hrefObject.type === "page" || hrefObject.type === "view") {
				var hashTag = (href.indexOf(self.config.hashTagDelimiter) === -1 ? "" : href.split(self.config.hashTagDelimiter)[1]);
				if (!isStandard && isEmpty(hashTag)) {
					if (hrefObject.isAppRoute) {
						hashTag = hrefObject.route;
					} else {
						if (!isEmpty(hrefObject.route)) {
							hashTag = hrefObject.route + "/" + hrefObject.resource;
						} else {
							hashTag = hrefObject.resource;
						};
						if (hrefObject.view) {
							hashTag = hashTag + self.config.viewOrQualifiedNameDelimiter + hrefObject.view;
						};
					};
					if (href.indexOf(self.config.argsDelimiter) !== -1) {
						hashTag = hashTag + self.config.argsDelimiter + href.split(self.config.argsDelimiter)[1];
					};
				};
				hrefObject.hashTag = hashTag;
			};
			
			// return
			return hrefObject;
		},
		
		// get current url
		// returns (string): current fluid:// protocol based url
		current: function() {
			// CAUTION: this somehow does not work on IE - but work in Chrome
			// so because of that if a URL is pasted in a new tab, it will
			// not respect the #part in IE - since it just isn't there and therefore
			// will start from home
			// but in chrome, it will start on that page
			var href = window.location.href;
			if (href.indexOf(self.config.hashTagDelimiter) === -1) {
				// let it set home page url
				href = self.href.home();
			} else {
				// let it set defined url using fluid:// protocol
				href = self.config.fluidProtocol + href.split(self.config.hashTagDelimiter)[1]; // pick second part only
			};
				
			// unconfigured framework scenario
			if (isEmpty(href)) {
				href = self.config.fluidProtocol; // just set it to empty protocol
			};
				
			// return
			return href;
		},

		// get home url
		// returns (string): current fluid:// protocol based url
		home: function() {
			var href = "";
			if ($f.app && $f.app.config && $f.app.config.defaultPageUrl) {
				href = $f.app.config.defaultPageUrl;
			} else if ($f.config.options.defaultPageUrl) {
				href = $f.config.options.defaultPageUrl;
			};
			
			// return
			return href;
		}
	};
	
	// HTML file operations
	this.HTML = {
		// html content pre/post load processors
		// order or processing is not guranteed
		loadProcessors: {
			// post-load processors
			post: {
				// intercept hyperlinks 
				// params:
				//	elementId (string): DOM element id where html is just appended/replaced
				//	context (object): context object that may have required information to process
				// returns (void): 
				interceptHyperlinks: function(elementId, context) {
					// check if not to be processed
					var isSkipProcessing = false;
					if (isDefined(context.isSkipHyperlinkInterception)) {
						isSkipProcessing = context.isSkipHyperlinkInterception;
					};
					
					// process, if not to be skipped 
					if (!isSkipProcessing) {
						var element = null;
						if (elementId === "") {
							element = $("body");
						} else {
							element = $("#" + elementId);
						};
						if (element.length !== 0) {
							self.HTML.layout.hyperlinkSetup(element.find("a"));
						};
					};
				}
			}
		},
		
		// layout HTML operations
		layout: {
			// setup hyperlink interception on selector's click action
			// to handle framework style urls
			// params:
			//	selector (element): jQuery selector result to apply hyperlink interception on
			// returns (void):		
			hyperlinkSetup: function(selector) {
				// apply hyperlink interception to intercept all internal and external navigation calls
				// if href function is available - via navigator feature inclusion
				if (self.href) {
					selector.click(function(){
						// get href
						var href = $(this).attr('href');
			
						var isProcess = false;
						if (href) {
							if (href === "#") {
								// go and process default
								isProcess = true;
							} else if (this.attributes && this.attributes["fluid-noIntercept"]) {
								// go and process default
								isProcess = true;							
							} else {
								// return (false, if processed (so it does not perform default navigation), true otherwise)
								isProcess = !self.href(href);
							};
						};
						
						return isProcess; 
					});
				};
			}
		}
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: navigator
  *  Dependencies: 
  *		- fluid core
  * 	- jQuery.ba.hashchange v1.3 (or upwards)
  *			- http://benalman.com/projects/jquery-hashchange-plugin/
  *			- https://raw.github.com/cowboy/jquery-hashchange/v1.3/jquery.ba-hashchange.js
  * 		- License: MIT/GPL
  *  Functionality:
  *		- this plugin provides core navigational functionality. It plays a major role in making
  *       transition from one page to another.
  *		- it does not process any other plugins although call several page navigation lifecycle
  *		  related event handlers on app, master page and page. 
  *
  */
(function($f) {	$f.extend.system("navigator", "nav", "08434cde-ceca-4830-89c6-d4b66001be70", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

	var masterPageToLoad = "";
	var viewGoingOut = null;
	var viewTimer = null;

	// keeps track of time taken by last view refresh (only if isDebug = true)
	var viewPerformanceCounter = function(action) {
		switch(action.toLowerCase()) {
			case "set": {
				if ($f.config.options.isDebug) {
					viewTimer = (new Date().getTime()).toString();
				};
				break;
			};
			case "clear": {
				if ($f.config.options.isDebug && viewTimer) {
					var lastValue = Number(viewTimer);
					viewTimer = null;
					if (lastValue !== -1) {
						var msToRefresh = ((new Date().getTime() - lastValue)/1000);
						window.status = msToRefresh.toString() + " seconds";
					};
				};
				break;
			};
		};
	};
		
	// when everything is done (either page with no-view is loaded OR page with view is loaded OR view is switched)
	var onEverythingDone = function() {
		// reset other states
		self.state.isNavigatingBecauseOfOrientationChange = false;
		
		// call navigation complete
		if (isFunction(self.vars.onNavigationCompleteCallBack)) {
			// completes the navigation cycle (once all plugins are loaded)
			$.doTimeout("navigateCompleteCheck", self.vars.allPluginLoadCheckInterval, function() {
				// check if all plugins are loaded
				var isRemaining = false;
				$.each($f.all.plugins(), function(i, plugin) {
					if (!plugin.handle.isIncludeProcessed) {
						isRemaining = true;
						return false; // break
					};
				});
				
				// if nothing is remnaining, clear and call navigate complete
				if (!isRemaining) {
					// inform app that page is loaded
					if ($f.app && isFunction($f.app.onAfterPageLoad)) {
						$f.app.onAfterPageLoad();
					};											
				
					// call navigation complete
					var onNavigationComplete = self.vars.onNavigationCompleteCallBack;
					self.vars.onNavigationCompleteCallBack = null; // reset
					onNavigationComplete();
					
					// done
					return false; // so it does not poll
				} else {
					// return
					return true; // so it polls again											
				};
			});
		};
	};
	
	// what do to after view layout is loaded
	var onViewLayoutLoadComplete = function() {
		// certain things are done only when view is being loaded for first time
		if ($f.view.isFirstNavigation.get()) {
			// call onBeforeDataLoad for view
			if (isFunction($f.view.onBeforeDataLoad)) {
				$f.view.onBeforeDataLoad();	
			};		
			
			// load data objects of view
			if ($f.dataObjects) {
				$f.dataObjects.load($f.view);
			};			
				
			// load custom data objects for view
			if (isFunction($f.view.loadCustomDataObjects)) {
				$f.view.loadCustomDataObjects();	
			};

			// call onAfterDataLoad for view
			if (isFunction($f.view.onAfterDataLoad)) {
				$f.view.onAfterDataLoad();		
			};
			
			// apply data bindings
			if ($f.dataBinder) {
				$f.dataBinder.applyBindings($f.view);
			};
			
			// call onAfterLoad for view
			if (isFunction($f.view.onAfterLoad)) {
				$f.view.onAfterLoad();
			};

			// let view do any more custom logic before onNavigationComplete is called
			// this is defined in base, so no need to check for presence
			$f.view.beforeNavigationComplete();
		};
		
		// call onBeforeNavigateOut for last active - view
		// new view reference is already in $f.view
		if (viewGoingOut) {
			if (isFunction(viewGoingOut.onBeforeNavigateOut)) {
				viewGoingOut.onBeforeNavigateOut($f.view);	
			};			
		};
		
		// call onBeforeNavigateIn for view
		if (isFunction($f.view.onBeforeNavigateIn)) {
			$f.view.onBeforeNavigateIn(viewGoingOut);
		};		
		
		// apply view transition
		var effectFunctionName = "show"; // inbuilt default
		var effectFunction = null;
		var effectArgs = null;
		if ($f.view.config && $f.view.config.transitionEffect) {
			if (isString($f.view.config.transitionEffect)) {
				effectFunctionName = $f.view.config.transitionEffect;
			} else {
				if ($f.view.config.transitionEffect.name) {
					effectFunctionName = $f.view.config.transitionEffect.name;
				};
				if ($f.view.config.transitionEffect.args) {
					effectArgs = $f.view.config.transitionEffect.args;
				};
			};
		};
		if (isFunction(self.viewTransitionEffects[effectFunctionName])) {
			effectFunction = self.viewTransitionEffects[effectFunctionName];
		};
		var currentViewContainer = (viewGoingOut ? $f.env.container.view(viewGoingOut) : "");
		var newViewContainer = $f.env.container.view($f.view);
		effectFunction(currentViewContainer, newViewContainer, effectArgs);
		
		// call onAfterNavigateIn for view
		if (isFunction($f.view.onAfterNavigateIn)) {
			$f.view.onAfterNavigateIn(viewGoingOut);
		};
		
		// inform page that a view was loaded/switched
		if (isFunction($f.page.onAfterViewSwitch)) {						
			$f.page.onAfterViewSwitch(viewGoingOut, $f.view);
		};
		
		// everything is done
		onEverythingDone();
		
		// view is changed now
		viewPerformanceCounter("clear");
	};
	
	// what to do after page layout is loaded
	var onPageLayoutLoadComplete = function() {
		// call onBeforeDataLoad for app, master and page
		if ($f.app && isFunction($f.app.onBeforeDataLoad)) {
			$f.app.onBeforeDataLoad();	
		};		
		if ($f.master && isFunction($f.master.onBeforeDataLoad)) {
			$f.master.onBeforeDataLoad();		
		};
		if (isFunction($f.page.onBeforeDataLoad)) {
			$f.page.onBeforeDataLoad();
		};	
		
		// load data objects
		if ($f.dataObjects) {
			if ($f.app) {
				$f.dataObjects.load($f.app);
			};
			if ($f.master) {
				$f.dataObjects.load($f.master);
			};
			$f.dataObjects.load($f.page);
		};
		
		// load custom data objects for app, master and page
		if ($f.app && isFunction($f.app.loadCustomDataObjects)) {
			$f.app.loadCustomDataObjects();	
		};
		if ($f.master && isFunction($f.master.loadCustomDataObjects)) {
			$f.master.loadCustomDataObjects();
		};
		if (isFunction($f.page.loadCustomDataObjects)) {
			$f.page.loadCustomDataObjects();
		};
		
		// call onAfterDataLoad for app, master and page
		if ($f.app && isFunction($f.app.onAfterDataLoad)) {
			$f.app.onAfterDataLoad();	
		};		
		if ($f.master && isFunction($f.master.onAfterDataLoad)) {
			$f.master.onAfterDataLoad();		
		};
		if (isFunction($f.page.onAfterDataLoad)) {
			$f.page.onAfterDataLoad();
		};									
		
		// apply data bindings
		if ($f.dataBinder) {
			// apply all bindings as defined in app, master and page
			if ($f.app) {
				$f.dataBinder.applyBindings($f.app);
			};
			if ($f.master) {
				$f.dataBinder.applyBindings($f.master);
			};
			$f.dataBinder.applyBindings($f.page);									
		};

		// call onAfterLoad for page and master
		if (isFunction($f.page.onAfterLoad)) {
			$f.page.onAfterLoad();	
		};
		if ($f.master && isFunction($f.master.onAfterLoad)) {
			$f.master.onAfterLoad();
		};									
		
		// show navigation error if any
		if (self.vars.navigationError != "") {
			$("#" + $f.env.container.error()).html(self.vars.navigationError);
		};		
		
		// reset error
		self.vars.navigationError = "";
		
		// let page do any more custom logic before onNavigationComplete is called
		// this is defined in base, so no need to check for presence
		$f.page.beforeNavigationComplete();
		
		// since page is now loaded, check if any view is defined in href
		// let it load now
		if ($f.page.href.get().view) {
			// calling again will initiate the view navigation this time
			// because this time current jsfile and this jsfile will be same
			self.go($f.page.href.get());
			
			// this will eventually end in onViewLayoutLoadComplete
		} else {
			// everything is done
			onEverythingDone();
		};
	};
	
	// what to do after master page layout is loaded
	var onMasterPageLayoutLoadComplete = function() {
		// load page layout
		var pageLayout = "";
		if ($f.page.config && $f.page.config.layout) {
			pageLayout = $f.page.config.layout;
		};
		pageLayout = $f.page.p.getLayout(pageLayout, $f.page);
		if (isEmpty(pageLayout)) {
			pageLayout = 'html: <p>Framework needs to be configured.</p>';
		};
		$f.document.HTML.layout.loadASync(pageLayout, $f.env.container.page(), $f.page, "", function(data, isError) {
			// continue irrespective of error
			onPageLayoutLoadComplete();
		});
	};
	
	// what to do after host layout is loaded
	var onHostLayoutLoadComplete = function() {
		// load master page layout
		var masterPageLayout = "";
		var contextPlugin = null;
		if ($f.master) {
			if ($f.master.config && $f.master.config.layout) {
				masterPageLayout = $f.master.config.layout;
			};
			masterPageLayout = $f.page.p.getLayout(masterPageLayout, $f.master);
			contextPlugin = $f.master;
		};
		
		// use default embedded html format to define a default master page layout structure if master page functionality is not available
		if (isEmpty(masterPageLayout)) {
			masterPageLayout = 'html: <div id="_page"><div id="page"></div></div>';	
			contextPlugin = $f.app;			
		};
		
		// load layout
		$f.document.HTML.layout.loadASync(masterPageLayout, $f.env.container.master(), contextPlugin, "", function(data, isError) {
			// continue irrespective of error
			onMasterPageLayoutLoadComplete();
		});
	};
		
	// what to do after master page JS load 
	var onMasterPageLoadComplete = function() {
		// if master functionality is available - but master was not loaded
		if ($f.has.feature("masterPages") && !$f.master) {
			// load default master if error or nothing was defined
			$f.master = $f.master_default;
		};
		
		// load master page url
		if ($f.master) {
			$f.master.url = $f.utils.object.factory.getNew.readOnlyProperty(masterPageToLoad); 
		};

		// setup emulator if required
		if ($f.emulator && $f.emulator.isEmulating.get()) {
			$f.emulator.on();
		};
		
		// call onOrientationChange if required
		if (self.state.isNavigatingBecauseOfOrientationChange) {
			// let master and page reconfigure themselves
			if ($f.master && isFunction($f.master.onOrientationChange)) {
				$f.master.onOrientationChange();
			};
			if (isFunction($f.page.onOrientationChange)) {
				$f.page.onOrientationChange();
			};
		};
		
		// call onBeforeLoad for master and page
		if ($f.master && isFunction($f.master.onBeforeLoad)) {
			$f.master.onBeforeLoad();
		};
		if (isFunction($f.page.onBeforeLoad)) {
			$f.page.onBeforeLoad();
		};

		// load host layout if available
		var hostLayout = "";
		if ($f.app) {
			// pick from current theme - later fallback to default defined at app level
			if ($f.app.has.feature("themes")) {
				var theme = $f.app.theme();
				if (theme && theme.layout) {
					hostLayout = $f.page.p.getLayout(theme.layout);
				};
			};
			if (isEmpty(hostLayout) && $f.app.config && $f.app.config.defaultHostLayout) {
				hostLayout = $f.page.p.getLayout($f.app.config.defaultHostLayout);
			};
		};

		// use default embedded html format to define a default host layout structure if not defined anywhere
		if (isEmpty(hostLayout)) {
			hostLayout = 'html: <div id="_master"><div id="master"></div></div>';						
		};
		
		// load host layout
		$f.document.HTML.layout.loadASync(hostLayout, $f.env.container.host(), $f.app, "", function(data, isError) {
			// continue irrespective of error
			onHostLayoutLoadComplete();
		});						
	};
		
	// what to do after page JS load 
	var onPageLoadComplete = function() {
		// load default page, if page is not defined or could not load
		var isDefaultPageLoaded = false;
		if (!$f.page) {
			// set navigation error, if not already set
			var errorText = "Failed to navigate to page '" + self.state.currentHref.url + "'.";
			if (self.vars.navigationError == "") {
				self.vars.navigationError = errorText;
			};					
			$f.error(errorText, false, false);						
			
			// load default page
			$f["page"] = $f["page_default"];
			isDefaultPageLoaded = true;
		} else {
			// set reload state on page 
			// if app is restarting or if session is new, then reload is definitely false
			// else it depends on navigator's reload state
			if (($f.state && $f.state.isAppRestarting) || ($f.sess && $f.sess.isNew.get())) {
				$f.page.isReload = $f.utils.object.factory.getNew.readOnlyProperty(false); // because application was reset or restarted
			} else {
				$f.page.isReload = $f.utils.object.factory.getNew.readOnlyProperty(self.state.isReload);
			};					
			
			// check access to page, if required
			if ($f.sec && $f.sec.auth) {
				if (!$f.sec.auth.hasAccess.toPage($f.page)) {
					// set navigation error, if not already set
					var errorText = "Access is denied for page '" + self.state.currentHref.url + "'.";
					if (isEmpty(self.vars.navigationError)) {
						self.vars.navigationError = errorText;
					};					
					$f.error(errorText, false, false);						
				
					// load default page
					$f["page"] = $f["page_default"];
					isDefaultPageLoaded = true;
				};
			};
		};

		// update window title - only when this is not a view
		if (!self.state.currentHref.view) {
			var title = $f.page.info.title;	
			if ($f.app && title && $f.app.info.title) {
				title = title + " - " + $f.app.info.title;
			};
			document.title = title;	
		};
		
		// define page href
		$f.page.href = $f.utils.object.factory.getNew.readOnlyProperty(self.state.currentHref);
		
		// define page url 
		$f.page.url = $f.utils.object.factory.getNew.readOnlyProperty(self.state.currentHref.url);
		
		// define page args
		$f.page.args = $f.utils.object.factory.getNew.readOnlyProperty(self.state.currentHref.args);
		
		// add page to history - only when this is not a view
		if (!self.state.currentHref.view) {
			self.history.p.add(self.state.currentHref);
		};
		
		// reset reload flag (back to true - to handle F5 case)
		self.state.isReload = true;
		
		// look for master page (only if default page is not loaded - otherwise use default master also)
		if (!isDefaultPageLoaded && $f.app) {
			if ($f.app.has.feature("themes")) {
				var theme = $f.app.theme();
				if (theme && theme.masterPage) {
					masterPageToLoad = theme.masterPage;
				};
			};
			
			// fall back to default at app level
			if (isEmpty(masterPageToLoad) && $f.app.config && $f.app.config.defaultMasterPage) {
				masterPageToLoad = $f.app.config.defaultMasterPage;
			};
		};
		
		// load master page if required
		// and master page functionality is available
		if (masterPageToLoad != "" && $f.has.feature("masterPages")) {
			// load master page
			var masterPageUrl = masterPageToLoad;
			$f.extend.master.fromFile(masterPageUrl, function(data, isError) {
				if (isError) {
					// master page file could not be loaded
					// set navigation error, if not already set
					var errorText = "Master page '" + masterPageUrl + "' could not be loaded.";
					if (isEmpty(self.vars.navigationError)) {
						self.vars.navigationError = errorText;
					};					
					$f.error(errorText, false, false);
				};
				
				// call page load complete
				onMasterPageLoadComplete();									
			});
		} else {
			// call page load complete
			onMasterPageLoadComplete();					
		};
	};	
	
	// what to do after view JS load
	var onViewLoadComplete = function(href, view) {
		// check if args are changed, since this view was last opened
		var isArgsChanged = (view.href.get().argsString && view.href.get().argsString !== href.argsString ? true : false);
		
		// define view href
		view.href = $f.utils.object.factory.getNew.readOnlyProperty(href);
	
		// check access to view, if required
		if ($f.sec && $f.sec.auth) {
			if (!$f.sec.auth.hasAccess.toView(view)) {
				$f.error("Access is denied for view '" + href.url + "'.", false, false);

				// don't do anything further
				return;
			};
		};

		// inform page that a view is about to load/switch
		if (isFunction($f.page.onBeforeViewSwitch)) {						
			if (!$f.page.onBeforeViewSwitch($f.view, href)) {
				// since page stopped switch of view, don't do anytthing further
				return;
			};
		};

		// reset $f.view reference to this new view getting active and hold on
		// old view reference if any, in a closure variable
		viewGoingOut = $f.view;
		$f.view = view;
		
		// update window title 
		var title = $f.view.info.title;
		if (title && $f.page.info.title) {
			title = title + " - " + $f.page.info.title;
		};
		if ($f.app && title && $f.app.info.title) {
			title = title + " - " + $f.app.info.title;
		};
		document.title = title;	
	
		// define view url 
		$f.view.url = $f.utils.object.factory.getNew.readOnlyProperty(href.url);
		
		// define view args
		$f.view.args = $f.utils.object.factory.getNew.readOnlyProperty(href.args);
		
		// define isArgsChanged property
		$f.view.isArgsChanged = $f.utils.object.factory.getNew.readOnlyProperty(isArgsChanged);
		
		// add view to history
		self.history.p.add(href);
		
		// load current
		self.state.currentHref = href;

		// call onOrientationChange if required
		if (self.state.isNavigatingBecauseOfOrientationChange) {
			// let view reconfigure itself
			if (isFunction($f.view.onOrientationChange)) {
				$f.view.onOrientationChange();
			};			
		};
		
		// certain things are done only when view is being loaded for first time
		// or if there is a change in arguments
		if ($f.view.isFirstNavigation.get() || $f.view.isArgsChanged.get()) {
			// call onBeforeLoad for view
			if (isFunction($f.view.onBeforeLoad)) {
				$f.view.onBeforeLoad();
			};		
			
			// load view layout
			var viewLayout = "";
			if ($f.view.config && $f.view.config.layout) {
				viewLayout = $f.view.config.layout;
			};
			viewLayout = $f.page.p.getLayout(viewLayout, $f.view);
			if (isEmpty(viewLayout)) {
				viewLayout = 'html: </ br>';
			};
			
			// add view specific container in viewsContainerElementId
			var viewLayoutContainer = $f.env.container.view($f.view);
			var pageDIV = $f.env.container.page();
			if ($("#" + viewLayoutContainer).length === 0) {
				// add viewsContainerElementId if not found
				var viewsContainer = $f.env.container.views();
				var viewsDIV = $("#" + viewsContainer);
				if (viewsDIV.length === 0) {
					$("#" + pageDIV).append("<div id='" + viewsContainer + "'></div>");
					viewsDIV = $("#" + viewsContainer);
				};
				
				// add viewLayoutContainer in viewsDIV
				viewsDIV.append("<div id='" + viewLayoutContainer + "'></div>");
			};			
			$f.document.HTML.layout.loadASync(viewLayout, viewLayoutContainer, $f.view, "", function(data, isError) {
				// hide this view
				var viewLayoutDIV = $("#" + viewLayoutContainer);
				viewLayoutDIV.hide();
				
				// continue irrespective of error
				onViewLayoutLoadComplete();
			});			
		} else {
			// since layout is already loaded when not frst navigation
			// continue after layout load process
			onViewLayoutLoadComplete();
		};
	};
	
	// extend stcrural elements in startup html
	var extendStartupHtmlStructure = function() {
		// load styles required by this structure
		$f.document.CSS.styles.load("baseStructureCSSEx", '' +
			'#_topPane { top: 0; width: 100%; height: 0%; position: fixed; overflow: hidden; display: none; } \n' +
			'#_leftPane { top: 0%; left: 0; width: 0%; height: 100%; float: left; position: fixed; overflow: hidden; display: none; } \n' +
			'#_centerPane { top: 0%; left: 0%; width: 100%; height: 100%; float: left; position: fixed; overflow: auto; } \n' +
			'#_rightPane { top: 0%; right: 0; width: 0%; height: 100%; float: right; position: fixed; overflow: hidden; display: none; } \n' +
			'#_bottomPane { bottom: 0; width: 100%; height: 0%; float: bottom; position: fixed; overflow: hidden; display: none; } \n');
	
		// extend basic internally controlled structure for startup html
		var structureHtmlEx = '' + 
		'<div id="containerInfoBar"></div>' +
		'<div id="panes">' + 
			'<div id="_topPane"><div id="topPane"></div></div>' +
			'<div id="_middlePane">' + 
				'<div id="_leftPane"><div id="leftPane"></div></div>' +
				'<div id="_centerPane"><div id="centerPane">' + 
						'<div id="_emulator"><div id="emulator">' + 
								'<div id="_screen"><div id="screen">' +  
										'<div id="screenInfoBar"></div>' + 
										'<div id="waitWheel"></div>' +
										'<div id="_host"><div id="host">' + 
												'<div id="_master"><div id="master">' + 
													'<div id="_page"><div id="page"></div></div>' +
												'</div></div>' + 
										'</div></div>' + 
								'</div></div>' + 
						'</div></div>' + 
				'</div></div>' +
				'<div id="_rightPane"><div id="rightPane"></div></div>' +
			'</div>' +
			'<div id="_bottomPane"><div id="bottomPane"></div></div>' +
		'</div>';

		// add this structure to root structure
		// and move "unstructuredBody" under "screen"
		$("#" + $f.env.container.root()).append(structureHtmlEx).find("#" + $f.env.container.unstructuredBody()).detach().prependTo("#" + $f.env.container.screen());
	};
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "Navigator",
		description: "Adds client side navigation capabilities to framework."
	};

	// initialization handler
	// returns (boolean): 
	//	true: if success 
	//	false: if failed
	this.onInit = function() { 
		// extend startup html structure
		extendStartupHtmlStructure();
		
		// return
		return true; 
	};
	
	// unload handler
	// returns: (void)
	this.onUnload = function() {
		// start navigating out
		self.navigateOut();
	};
	
	// reset handler
	// returns: (void)
	this.onReset = function() {
		// ideally should clear history
		// but at the moment cannot clear
		// browser navigation history
	};
	
	// restart handler
	// returns: (void)
	this.onRestart = function() {
		// ideally should clear history
		// but at the moment cannot clear
		// browser navigation history
	};
	
	// state (contents here-in must be JSON serializable)
	// these are preserved across page refresh
	this.state = {
		// if this is a reload scenario (state default is true to handle browser F5 case)
		isReload: true,
		
		// if this is a navigation in history scenario
		isNavigationInHistory: false, 
		
		// if navigator is in navigation process
		isInNavigation: false,
		
		// current loaded page
		currentHref: null,
		
		// navigating to page
		navigatingToHref: null,
		
		// if navigation happened because of orientation change
		isNavigatingBecauseOfOrientationChange: false
	};
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = { 
		// any error that occured in navigation
		navigationError: "",
		
		// call back function which is to be called after view is rendered
		onNavigationCompleteCallBack: null,
		
		// if reload() call is to be skipped in go()
		isSkipReloadOnGo: false,
		
		// interval in milliseconds that is used in setInterval before navigation is called complete
		// this controls that all plguins are loaded before their ready is called
		allPluginLoadCheckInterval: 1,
		
		// if hash was last changed programatically
		wasHashUpdated: false
	};		
	
	// plugin configuration
	this.config = {
		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 400		
	};
		
	// returns if navigator is in reloading state
	this.isReloading = $f.utils.object.factory.getNew.stateProperty(self, "isReload");
	
	// returns if navigator is navigating in history
	this.isNavigatingInHistory = $f.utils.object.factory.getNew.stateProperty(self, "isNavigationInHistory");
	
	// navigate either to home page or completes the ongoing navigation
	// params:
	//	onNavigationComplete (function): call back function to inform that navigation is complete
	// returns (void):
	this.navigateIn = function(onNavigationComplete) {
		// continue previous navigation or goto home page
		var isContinue = false;
		var isSupressLoadingCurrentState = false;
		if (!self.state.isInNavigation) {
			if (isFunction(onNavigationComplete)) {
				// since call has come from onLoad, and no navigation is in progress
				// therefore either this is first load scenario or a reload scenario or
				// a url paste on browser scenario

				// check if there is a no current page url defined (which is being reloaded)
				// go and load home page
				if (isNull(self.state.currentHref)) {
					// let it set page configuration only and comeback here itself without reloading everything
					self.vars.isSkipReloadOnGo = true;
					
					// get current or default href
					var href = $f.document.href.split($f.document.href.current());
					self.go(href);
					
					// reset flag
					self.vars.isSkipReloadOnGo = false;						
				} else {
					// this generally caters to reload (F5) scenario
					// don't change any current-settings
					isSupressLoadingCurrentState = true;
					
					// set reload
					self.state.isReload = true;
				};
						
				// set continue to true
				isContinue = true;
			};
		} else {
			if (isFunction(onNavigationComplete)) {
				// since call has come from onLoad, and one navigation is already in progress (came here after reload)
				// therefore set continue to true
				isContinue = true;		
			};
		};

		// continue in special known cases
		if (isContinue) {
			// set callback function
			self.vars.onNavigationCompleteCallBack = onNavigationComplete;
		
			// load current
			if (!isSupressLoadingCurrentState) {
				self.state.currentHref = self.state.navigatingToHref;
			};

			// reset
			self.state.isInNavigation = false;
			self.state.navigatingToHref = null;
			
			// inform app that a new page is about to load
			if ($f.app && isFunction($f.app.onBeforePageLoad)) {						
				$f.app.onBeforePageLoad();
			};				
			
			// load page JS and perform further processing
			var pageJS = self.state.currentHref.jsFile;
			if (pageJS) {
				// load page
				$f.extend.page.fromFile(pageJS, function(data, isError) {
					if (isError) {
						// page file could not be loaded
						// set navigation error, if not already set
						var errorText = "Page '" + pageJS + "' could not be loaded.";
						if (isEmpty(self.vars.navigationError)) {
							self.vars.navigationError = errorText;
						};					
						$f.error(errorText, false, false);
					};
					
					// call page load complete
					onPageLoadComplete();								
				});
			} else {
				// set error
				if (isEmpty(self.vars.navigationError)) {
					self.vars.navigationError = "Page js is not specified.";
				};					
				
				// complete load cycle
				onPageLoadComplete();
			};
		};
	};
	
	// navigate out of current page
	// returns (void): 
	this.navigateOut = function() {
		// since page is unloading - means any view which is active will be navigating out
		// therefore - call before navigate out for active view
		if ($f.view && isFunction($f.view.onBeforeNavigateOut)) {
			$f.view.onBeforeNavigateOut(null);	
		};
	
		// inform app that page is about to unload
		if ($f.app && isFunction($f.app.onBeforePageUnload)) {
			$f.app.onBeforePageUnload();		
		};
	
		// save or clear data objects (custom and inbuilt) for app
		// app level data objects are always kept alive - therefore no checking is required
		// and that's why there is no implementation for clearDataObjects
		if ($f.app) {
			if (isFunction($f.app.saveCustomDataObjects)) {
				$f.app.saveCustomDataObjects();	
			};
			if ($f.dataObjects) {
				$f.dataObjects.save($f.app); 
			};			
		};
		
		// save or clear data objects (custom and inbuilt) for master
		if (self.state.isReload || ($f.master && $f.master.config && $f.master.config.isKeepDataStateAlive)) {
			if ($f.master && isFunction($f.master.saveCustomDataObjects)) {
				$f.master.saveCustomDataObjects();	
			};
			if ($f.dataObjects) {
				$f.dataObjects.save($f.master); 
			};
		} else {
			if ($f.master) {
				if (isFunction($f.master.clearCustomDataObjects)) {
					$f.master.clearCustomDataObjects();
				};
				if ($f.dataObjects) {
					$f.dataObjects.clear($f.master);
				};
			};
		};
		
		// save or clear data objects (custom and inbuilt) for page
		if (self.state.isReload || ($f.page && $f.page.config && $f.page.config.isKeepDataStateAlive)) {
			if (isFunction($f.page.saveCustomDataObjects)) {
				$f.page.saveCustomDataObjects();
			};
			if ($f.dataObjects) {
				$f.dataObjects.save($f.page);
			};					
		} else {
			if ($f.page) {
				if (isFunction($f.page.clearCustomDataObjects)) {
					$f.page.clearCustomDataObjects();
				};
				if ($f.dataObjects) {
					$f.dataObjects.clear($f.page);
				};
			};
		};
			
		// unload time process for all views - irrespective of which one is active 
		// and what order, since loaded views are always for current page, just iterate and call
		// for all views, if any current view is found
		if ($f.has.feature("views")) {
			var views = $f.all.views();
			$.each(views, function(i, view) {
				// save or clear data objects (custom and inbuilt) for view
				if (self.state.isReload || (view.config && view.config.isKeepDataStateAlive)) {
					if (isFunction(view.saveCustomDataObjects)) {
						view.saveCustomDataObjects();	
					};
					if ($f.dataObjects) {
						$f.dataObjects.save(view); 
					};
				} else {
					if (isFunction(view.clearCustomDataObjects)) {
						view.clearCustomDataObjects();
					};
					if ($f.dataObjects) {
						$f.dataObjects.clear(view);
					};
				};
				
				// call onBeforeUnload for view
				if (isFunction(view.onBeforeUnload)) {
					view.onBeforeUnload();
				};
			});
			
			// clear active view reference
			delete $f["view"];
		};
		
		// unload time process for all panes - irrespective of which one is open and which one is close 
		// and what order, since panes once loaded, remain loaded unless page refreshes, just iterate and call
		// for all panes
		if ($f.has.feature("panes")) {
			var panes = $f.all.panes();
			$.each(panes, function(i, pane) {
				// save or clear data objects (custom and inbuilt) for pane
				// irrespective of reload state, since certain panes which are loaded via URL 
				// might not come after a reload
				if ((pane.config && pane.config.isKeepDataStateAlive)) {
					if (isFunction(pane.saveCustomDataObjects)) {
						pane.saveCustomDataObjects();	
					};
					if ($f.dataObjects) {
						$f.dataObjects.save(pane); 
					};
				} else {
					if (isFunction(pane.clearCustomDataObjects)) {
						pane.clearCustomDataObjects();
					};
					if ($f.dataObjects) {
						$f.dataObjects.clear(pane);
					};
				};
				
				// call onBeforeUnload for pane
				if (isFunction(pane.onBeforeUnload)) {
					pane.onBeforeUnload();
				};
			});
		};

		
		// call onBeforeUnload for page and master
		if ($f.master && isFunction($f.master.onBeforeUnload)) {
			$f.master.onBeforeUnload();
		};
		if ($f.page && isFunction($f.page.onBeforeUnload)) {
			$f.page.onBeforeUnload();
		};
	};
	
	// navigate when device orientation is changed
	// returns (void):
	this.navigateOnOrientationChange = function() {
		if (!self.state.isReload) {
			// set state
			self.state.isNavigatingBecauseOfOrientationChange = true;
			
			// reload
			self.reload();
		};
	};
	
	// navigate when hash in the url is changed
	// returns (void): 
	this.navigateOnHashChange = function() {
		// process only when some hash was not updated programatically
		// the last time
		if (self.vars.wasHashUpdated) {
			// reset it once and go back to neutralize the effect
			self.vars.wasHashUpdated = false;
			
			// return
			return;
		};
		
		// page or view navigation
		var isPageNavigation = true;		
		var newHrefObject = $f.document.href.split($f.document.href.current());
		var oldHrefObject = self.state.currentHref;
		if (!isNull(oldHrefObject) && oldHrefObject.jsFile.toLowerCase() === newHrefObject.jsFile.toLowerCase() && 
			newHrefObject.type === "view" && $f.has.feature("views")) {
				// this is view navigation
				isPageNavigation = false;
		};

		// mark it as we are navigating in history
		// NOTE: it is assumed that hash change actually means
		// we are navigating backward or forward
		// because when we actually go to a new page, it 
		// navigates to new url after reload - so in that case its not
		// a hash change scenario AND when we navigate to a view it does
		// not come here because of wasHashUpdated being true once
		// ISSUE: although one case could be when user typed url himself
		// and then its not a navigation in history but that case is an issue 
		// at the moment
		self.state.isNavigationInHistory = true;
			
		// navigate to page or view
		if (isPageNavigation) {
			self.navigateTo(newHrefObject.url);
		} else {
			// go change view
			self.go(newHrefObject);
		};
	};
	
	// navigates to specified url
	// same as documeng.href(href) - with option to add arguments here
	// params:
	//	url (string): url on which to navigate to (any standard protocol and fluid:// is supported)
	//  args (object): arguments that needs to be passed along
	//                 any args in url will be replaced with these new args (completely)
	//				   NOTE: Only basic value types (number, bool, string, date) are supported. 
	//				         Hierarchical/Object/Array/Function values are ignored.
	// returns (void):
	this.navigateTo = function(url, args) {
		// build new url with args, if required
		if (args) {
			// ignore any args in url
			var argsDelimiter = $f.document.config.argsDelimiter;
			var argsSeperator = $f.document.config.argsSeperator;
			var argValueSeperator = $f.document.config.argValueSeperator;
			url = url.split(argsDelimiter)[0]; 
			
			// add new args
			var isFirst = true;
			$.each(args, function(name, value) {
				// add only for supported types
				if (value instanceof String || value instanceof Number || 
					value instanceof Boolean || value instanceof Date ||
					typeof value === 'string' || typeof value === 'number' || 
					typeof value === 'boolean') { 
					// add argsSeperator, if required
					if (!isFirst) {
						url = url + argsSeperator;
					} else {
						url = url + argsDelimiter;
						isFirst = false;
					};	
					
					// add arg
					url = url + name + argValueSeperator + value.toString();  
				};
			});
		};
		
		// forward to document
		$f.document.href(url);
	};
	
	// navigate to specified href object (only if this contains page or view definition)
	// params:
	//	href (object): href object (having page/view definition)
	//				   if not defined, it will go to configured home url
	// returns (void):
	this.go = function(href) {
		// set it back to navigate to complete current navigation, if it is already in navigation
		// in this case this new navigation call will be ignored
		if (self.state.isInNavigation) {
			$f.error("Already in navigation.", true, false);
			return;
		};
		
		// load home or current, if not specified
		if (!href) {
			var home = $f.document.href.home();
			if (!isEmpty(home)) {
				href = $f.document.href.split(home);
			} else {
				$f.error("No where to go.", true, false);
				return;
			};
		};

		// recheck - page or view navigation, as call may have come here directly as well
		// apart from navigateOnHashChange
		var isPageNavigation = true;		
		var oldHrefObject = self.state.currentHref;
		if (!isNull(oldHrefObject) && oldHrefObject.jsFile.toLowerCase() === href.jsFile.toLowerCase() && 
			href.type === "view" && $f.has.feature("views")) {
			// this is view navigation
			isPageNavigation = false;
		};

		// page or view navigation
		if (isPageNavigation) {
			// set reload state - based on if current url same as new url
			if (isNull(self.state.currentHref)) {
				self.state.isReload = false;
			} else {
				self.state.isReload = (self.state.currentHref.url.toLowerCase() === href.url.toLowerCase());
			};

			// set state
			self.state.isInNavigation = true;
			self.state.navigatingToHref = href;
			
			// reload startupHtml, this will end up in --> navigateIn()
			if (!self.vars.isSkipReloadOnGo) {
				self.reload();
			};
		} else {
			// start view change counter
			viewPerformanceCounter("set");
			
			// get view plugin, if loaded
			var view = null;
			var viewId = "";
			var viewJS = "";
			var viewKey = href.view;
			if ($f.page.views[viewKey] && $f.page.views[viewKey].viewId) {
				viewId = $f.page.views[viewKey].viewId;
				viewJS = $f.page.views[viewKey].view;
				view = $f.get.view.byId(viewId);
			};
					
			// if already loaded found
			if (view) {
				// reset first navigation
				view.isFirstNavigation = $f.utils.object.factory.getNew.readOnlyProperty(false);
				
				// load/change view
				onViewLoadComplete(href, view);					
			} else if (viewJS && viewId) {
				// load now
				$f.extend.view.fromFile(viewJS, viewId, function(data, isError) {
					if (isError) {
						// view file could not be loaded
						$f.error("View '" + viewJS + "' could not be loaded.", false, false);
					} else {
						// get view now
						view = $f.get.view.byId(viewId);
					};
			
					// load/change, if loaded
					if (view) {
						// set first navigation
						view.isFirstNavigation = $f.utils.object.factory.getNew.readOnlyProperty(true);
				
						// load/change view
						onViewLoadComplete(href, view);							
					};
				});
			};
		};
	};
	
	// go home
	// returns (void):
	this.goHome = function() {
		// forward
		self.go($f.document.href.split($f.document.href.home()));
	};
	
	// reload current page, same as F5 on browser or $f.page.refresh()
	// returns (void): 
	this.reload = function () { 
		// NOTE: Nothing else should be written here, if something is required to be done in this context 
		// do it on onUnload() in framework
		
		// refresh host (this will reload everything)
		// the URL must never change, because if this top-level-context (document's URL) changes and therefore
		// sessionStorage also gone - causing session memory to be cleaned. Therefore this is strictly have to be
		// one URL application
		// (call using delayed execution - to break call stack sequence issues)
		$f.exec.withDelay(function(){ 
			window.location.reload();		
		}); 
	};
	
	// available view transitions
	// can be extended using features
	this.viewTransitionEffects = {
		// plain show/hide (inbuilt default)
		// params:
		//	currentViewContainer (string): DOM element id which contains current view
		//								   (if this is empty, means no view is current)
		//	newViewContainer (string): DOM element id which contains new view that needs to appear now
		//  args (object): any effect arguments
		// returns (void):		
		show: function(currentViewContainer, newViewContainer, args) {
			// hide current view
			var element = null;
			if (currentViewContainer) {
				element = $("#" + currentViewContainer);
				if (element.length !== 0) {
					element.hide();
				};
			};
			
			// show new view
			if (newViewContainer) {
				element = $("#" + newViewContainer);
				if (element.length !== 0) {
					element.show();
				};
			};
		}
	};
	
	// navigation history controller
	this.history = {
		// go back one level in history
		// returns (void):
		back: function() {
			// go one up in browser history
			self.history.go(-1);
		},
		
		// go forward one level in history
		// returns (void):
		forward: function() {
			// go one next in browser history
			self.history.go(1);			
		},
		
		// returns the number of items in browser history
		// returns (number): count of items in browser history
		count: function() {
			// return length
			return window.history.length;
		},
		
		// go back (negative offset) or forward (positive offset) from current position in history
		// params:
		//	offset (number): how much to move back or forward
		// returns (void): 
		go: function(offset) {
			// forward
			window.history.go(offset);
		},
		
		// private functions 
		// not for public use
		// backward compatibility is not guranteed			
		p: {
			// adds page/view url to history
			// params:
			//	href (object): href object
			// returns (void):
			add: function(href) {
				// get route
				var route = href.hashTag;
				var hashTagDelimiter = $f.document.config.hashTagDelimiter;
				
				// page or view specific decision
				var isAdd = false;
				if (href.type === "page") {
					if (!self.state.isReload && (window.location.href.indexOf(hashTagDelimiter) !== -1) && 
						!self.state.isNavigationInHistory && route) {
						isAdd = true;
					};
				} else {
					if ((window.location.href.indexOf(hashTagDelimiter) !== -1) && 
						!self.state.isNavigationInHistory && route) {
						isAdd = true;
					};
				};
				
				// set flag
				// this flag ensures that all changes that were done manually - don't get processed 
				// via onHashChange a second time.
				// NOTE: this is a very special condition and cateres to various
				// navigation scenarios across pages and views and F5. Since in first
				// view navigation of a page, call comes here twice, this is 
				// very thoughtfully handled. If changed ever, page and views navigation related
				// all cases should be thoroughly cheked.
				if ((isAdd && href.type === "view") ||
					(!isAdd && !self.state.isReload && !self.state.isNavigationInHistory)) {
					self.vars.wasHashUpdated = true;
				};
					
				// add/update
				if (isAdd) {
					// add new entry to history
					window.location.hash = route;
				} else {
					// update same history entry without adding new entry in history
					window.location.replace(window.location.href.split(hashTagDelimiter)[0] + hashTagDelimiter + route);
				};
				
				// reset flags
				self.state.isNavigationInHistory = false;			
			}
		}
	};
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: bus
  *  Dependencies: 
  * 	- fluid core
  *  Functionality:
  *		- this plugin provides loosely coupled inter-components communication functionality.
  *		- it does process other plugins/objects to process following property/structure, if defined.
  *			> events: { namespace, ...events..., subscriptions, handlers}
  * 
  */
(function($f) { $f.extend.system("bus", "33f00f47-53d8-480e-9a1d-be7c88d265bf", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvv PRIVATE VARS, FUNCTIONS AND CLASSES vvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// fluid event class
	// params:
	//	sender (object): sender of the event
	// 	name (string): name of the event (generally defined with "." to scope well, e.g., "App.Licensing.CheckFailed"
	// returns (object): returns new instance of configured fluid event
	var fluidEvent = function(sender, name) {
		// event name
		this.name = name;

		// sender of the event
		this.sender = sender;
		
		// publish this event
		// params:
		//	arguments: event arguments (any number, type of) that are to be passed to handlers
		// returns (void):
		this.publish = function() {
			// forward to bus, if available
			self.publish(this.sender, this.name, arguments);
		};

		// subscribe to this event
		// params:
		//	eventHandlerOf (object): event handler is of object (for correct this context)
		//	handler (function): event handler function
		// returns (void):
		this.subscribe = function(eventHandlerOf, handler) {
			// forward to bus, if available
			self.subscribe(this.name, eventHandlerOf, handler);
		};
		
		// unsubscribe from this event
		// params:
		//	handler (function): event handler function
		// returns (void):
		this.unsubscribe = function(handler) {
			// forward to bus, if available
			self.unsubscribe(this.name, handler);
		};
	};	
	
	// fluid event subscriptions class
	// params:
	// 	name (string): handler function name
	// 	events (array): events to which this handler is bound to
	// returns (object): returns new instance of configured fluid subscriptions object	
	var fluidEventSubscriptions = function(handler, events) {
		// handler function name
		this.handler = handler;
		
		// events array
		this.events = events;
	};
	
	// event args class
	// params:
	//	sender: sender of the event
	//	name: fully qualified name of the event
	//	args (object): event arguments
	// returns (object): returns new instance of the onject
	var eventArgs = function(sender, name, args) {
		// sender of the event
		this.sender = sender;
		
		// fully qualified name of the event
		this.name = name;
		
		// event args, if any
		this.args = args;
		
		var _isCancelled = false;
		// set cancel flag
		this.cancel = function() {
			_isCancelled = true;
		};
		
		// check cancelled flag status
		this.isCancelled = function() {
			return _isCancelled;
		};
	};

	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin info
	this.info = {
		title: "In-memory Communication Bus",
		description: "Provides pure client side publisher/subscriber operations for components to interact amongst each other without any hard dependencies."
	};
	
	// plugin variables
	// value of these variables is NOT maintained across page refresh
	this.vars = {
		// list of published/subscribed events
		events: {}
	};

	// plugin configuration
	this.config = {
		// can this plugin configure other plugins
		// if this is set to true, after plugins are initialized, these will be
		// given to this plugin's configure method to do required configuration
		canConfigurePlugins: true,

		// zIndex of the plugin controls the sequence of calling
		// onLoad, onReady and onUnload handlers of the plugins
		// with respect to each other
		// valid values are between 0 to 99999. Values between 0 to 9999
		// and 90001 upwards are reserved for framework plugins. 
		// For custom plugins use any value between 10000 to 90000.
		zIndex: 350					
	};

	// configure given plugin 
	// this is called for each plugin if canConfigurePlugins is set to true
	// params:
	//	plugin (object): plugin object to configure
	//	isPerformOnLoadProcessAlso (boolean): if process that is otherwise done at onLoad of this
	//                                        this plugin otherwise should also be done now with
	//                                        this plugin, because this is being loaded after all
	//                                        batch processing is done at load time
	//	isReconfigureOnNewFeatureAdd (boolean): if reconfiguration of plugin is required because
	// 										    a new feature is added to plugin which may have added
	//											some members those required reconfiguration	
	// returns (void):	
	this.configure = function(plugin, isPerformOnLoadProcessAlso, isReconfigureOnNewFeatureAdd) {
		// configure events
		if (plugin && plugin.events) {
			// get nameapce
			var namespace = "";
			if (plugin.events.namespace) {
				namespace = plugin.events.namespace + ".";
			};
			
			// configure events
			var nameLC = "";
			var knownNames = "'namespace', 'subscriptions', 'handlers', ";
			$.each(plugin.events, function(name, value) {
				if (value && !(plugin.events[name] instanceof fluidEvent)) {
					// ignore known names which form part of the events infrastructure
					nameLC = name.toLowerCase();
					if (knownNames.indexOf("'" + nameLC + "'") === -1) {
						// create and assign fluidEvent instance
						plugin.events[name] = new fluidEvent(plugin, namespace + value);
					};
				};
			});
		};	

		// configure subscriptions with corrosponding handlers
		if (plugin && plugin.events && plugin.events.subscriptions && plugin.events.handlers) {
			// process each subscription
			$.each(plugin.events.subscriptions, function(name, value) {
				if (value && !(plugin.events.subscriptions[name] instanceof fluidEventSubscriptions)) {
					// if defined handler exists
					if (isFunction(plugin.events.handlers[name])) {
						// bind to each defined event
						var value2 = value;
						if (!isArray(value2)) {
							value2 = [];
							value2.push(value); // to support simple string for single event
						};
						$.each(value2, function(i, eventName) {
							if (!isEmpty(eventName)) {
								self.subscribe(eventName, plugin, plugin.events.handlers[name]);
							};
						});
						
						// create an assign an object to define that this handler is processed
						plugin.events.subscriptions[name] = new fluidEventSubscriptions(name, value2);
					};
				};
			});	
		};				
	};

	// publish an event
	// params:
	//	sender (object): sender of the event
	//	eventName (string): name of the event to publish
	//	args (array): event arguments that are to be passed to handlers
	// returns (void):
	this.publish = function(sender, eventName, args) {
		if (self.vars.events[eventName]) {
			// create args
			var theEventArgs = new eventArgs(sender, eventName, args);
		
			// process each subscriber, unless cancelled by a handler
			$.each(self.vars.events[eventName], function(i, item) {
				if (isFunction(item.handler)) {
					// call subscriber with passed arguments (sync)
					item.handler.apply(item.owner, [theEventArgs]);
					
					// exit, if cancelled
					if (theEventArgs.isCancelled()) {
						return false; // break
					};
				};
			});
		};
	};

	// register subscriptiopn to an event
	// params:
	//	eventName (string): name of the event to subscribe to
	//	eventHandlerOf (object): event handler is of object (for correct this context)
	//	eventHandler (function): event handler function
	// returns (void):
	this.subscribe = function(eventName, eventHandlerOf, eventHandler) {
		if (eventHandler && eventHandlerOf && isFunction(eventHandler)) {
			if (self.vars.events[eventName]) {
				var isFound = false;
				$.each(self.vars.events[eventName], function(i, handler) {
					if (isFunction(handler) && handler === eventHandler) {
						isFound = true;
						return false; // break
					};
				});
				if (!isFound) {
					if (!isArray(self.vars.events[eventName])) {
						self.vars.events[eventName] = [];
					};
					self.vars.events[eventName].push({handler: eventHandler, owner: eventHandlerOf});
				};
			} else {
				// add
				self.vars.events[eventName] = [];
				self.vars.events[eventName].push({handler: eventHandler, owner: eventHandlerOf});
			};
		};
	};
	
	// unsubscribe from an event
	// params:
	//	eventName (string): name of the event to unsubscribe from
	//	eventHandler (function): event handler function
	// returns (void):
	this.unsubscribe = function(eventName, eventHandler) {
		if (eventHandler && isFunction(eventHandler)) {
			if (self.vars.events[eventName]) {
				var foundAt = -1;
				$.each(self.vars.events[eventName], function(i, item) {
					if (isFunction(item.handler) && item.handler === eventHandler) {
						foundAt = i;
						return false; // break
					};
				});
				if (foundAt !== -1) {
					// remove this element
					self.vars.events[eventName].splice(foundAt, 1);
				};
			};
		};			
	};
	
	// unload handler
	// returns: (void)
	this.onUnload = function() {
		// unwire all events 
		self.vars.events = {};
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Feature: appBase
  *	 Target: $f
  *  Dependencies: 
  *		- fluid core
  *  Functionality:
  *		- this adds app feature to framework core
  *
  */
(function($f) {	$f.extend.feature("appBase", "root", "a905cb26-05ab-40a5-98f7-568ddddbcc56", function(self) {

	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv FEATURE DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// feature info
	this.featureInfo = {
		title: "App Base",
		description: "Add app functionality to core framework."
	};	

	// feature only (non-merged) handle
	this.featureHandle = {
		// if this is a system feature
		isSystemFeature: true
	};

	// add to extend function
	this.FUNC_extend = {
		// forwards to extend
		app: function(id, extender) {
			// forward
			return $f.extend("app", id, extender);
		}
	};

	// private functions 
	// not for public use
	// backward compatibility is not guranteed
	this.p = {
		// plugin functionality
		plugins: {
			// plugin types
			types: {
				app: "app"
			},

			// feature targets
			// returns (array): returns an array of plugin objects of a particular type on which a feature 
			//                  is to be added when requested
			featureTargets: {
				app: function() {
					// create list
					var plugins = [];
					if ($f.app) {
						plugins.push($f.app);
					};
					
					// return
					return plugins;
				}	
			},
			
			// plugin classes
			// convention here is that except pluginBase, which is base of all plugins,
			// for every other type of plugin, the name should be "<typeName>PluginBase"
			// where <typeName> is the string defined for type in plugins.types above
			classes: {
				// extended definition for app plugin - over base definition
				appPluginBase: function(self) {
					// plugin handle
					this.handle = {
						// if app plugin
						isAppPlugin: true
					};
					
					// plugin configuration
					this.config = {
						// zIndex of the plugin controls the sequence of calling
						// onLoad, onReady and onUnload handlers of the plugins
						// with respect to each other
						// valid values are between 0 to 99999. Values between 0 to 9999
						// and 90001 upwards are reserved for framework plugins. 
						// For custom plugins use any value between 10000 to 90000.
						zIndex: 9999
					};
					
					// called when application is in offline mode and
					// its offline cache update is completed
					// params:
					//	isError (boolean): if there was an error in cache download/update
					//	isFirstDownload (boolean): if cache was downloaded first time on this computer, this
					//			                   will be true when very first time cache is updated on this
					//							   computer, for all other times, this will be false
					// returns (void):
					this.onOfflineCacheUpdate = function(isError, isFirstDownload) {
						// NOTE: this is default implementation, this can be 
						// replaced by a custom implementation, if required. E.g.,
						// for the sake of localization, if not for anything else
						
						// show information on info bar
						var message = "";
						if (isError) {
							message = "An error was observed in updating offline cache. " + $f.info.title + " will work only in online mode.";
							if ($f.infoBar) {
								$f.infoBar(message, "warning");
							} else {
								$f.alert(message);
							};
						} else if (isFirstDownload) {
							message = this.info.title + " is cached now and can work in offline mode.";
							if ($f.infoBar) {
								$f.infoBar(message, "info");
							} else {
								$f.alert(message);
							};
						} else {
							message = "A new update of " + this.info.title + " is downloaded. You should <a href='fluid://environment/offline/switchToNewUpdate.func'>refresh now</a> to start using it.";
							if ($f.infoBar) {
								$f.infoBar(message, "info");
							} else {
								$f.alert(message);
							};
						};
					};
					
					// returns a secret key used in encryption
					// returns (string): key string
					this.secretKey = function() {
						return "258a61d6-ff89-4a09-97ec-eb563a8347ee"; // default inbuilt random secret key
					};
					
					// called when an async request to write a file on server is received by environment
					// this should write file to server in user's context using some application service
					// and then callback the given function
					// params: 
					//	file (string): name of the file that is to br written to (can have placeholders in it)
					//  charset (string): chartset with which file is encoded  (empty means ASCII)
					//	fileContent (string): file content that is to be written
					//  data (object): data that is to be passed back to callback function
					//  callback (function): callback function that will be called after file is written
					//						 signature of this function should be: void callBackFunc(data, isError);			
					// returns (void):
					this.onWriteToServerRequest = function(file, charset, fileContent, data, callback) {
						// default implementation is to just callback with error flag
						$f.error("Write to server is not implemented.", true, false);
						if (isFunction(callback)) {
							callback(data, true);
						};
					};
				}
			}
		}
	};	
}); }(fluid));/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  Plugin: app
  *  Dependencies: 
  * 	- $f
  *  Functionality:
  *		- this app plugin provides a general purpose app placeholder definition.
  *		- it does not process any other plugins.
  * 
  */
(function($f) { $f.extend("app", "96ec9e2a-d194-4268-a4f4-d4af31e65e59", function(self) {
	
	"use strict";
	
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvv PLUGIN DEFINITION  vvvvvvvvvvvvvvvvvvvvvvvvvv
	// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
	
	// plugin handle
	this.handle = {
		// if system plugin
		isSystemPlugin: true,
		
		// if app plugin
		isAppPlugin: false
	};
	
	// plugin info
	this.info = {
		title: "Default Application",
		description: "Application plugin, used as default placeholder when no custom application plugin is defined."
	};
}); }(fluid));
/**
  * fluid - portable application framework
  * Copyright (c) 2012-2013, Vikas Burman, all rights reserved.
  * 
  * Licensed under the terms of the MIT license. You are free to use 'fluid' under any open source or 
  * commercial project, as long as this copyright header is left intact.
  * 
  * An explicit credit notice by using tiny "crafted on fluid" logo, which links back to the commercial site
  * of the project, is desired though not bounded by licensing terms.
  * 
  *     Project: http://fluidjs.codeplex.com/
  *     License: http://fluidjs.codeplex.com/license
  *        Blog: http://fluidjs.vikasburman.com
  * 
  *  File: AssembleComplete
  *  Dependencies: 
  * 	- None
  *  Functionality:
  *		- this marks completion of fluid assembly.
  *
  */
(function(window) {

	"use strict";
	
	// mark done
	if (window.fluid) {
		window.fluid.vars.isAssemblyDone = true;
	};
	
}(window));
